Fetch and track some remote branch, but to a new worktree

331 Views Asked by At

How can I fetch a branch from a repository but checkout to a new worktree?

Something like:

> git fetch origin releases/gcc-13
From git://gcc.gnu.org/git/gcc
 * branch                    releases/gcc-13 -> FETCH_HEAD
> git worktree add ../gcc-13 releases/gcc-13
fatal: invalid reference: releases/gcc-13

What I do not want is to checkout that branch to the current working directory (where .git is located) but to a new folder ../gcc-13.

git branch does not show releases/gcc-13. AFAIU I'd have to do something like

> git checkout --track origin/releases/gcc-13

but that would checkout gcc-13 to the current path, which is not what I want.

2

There are 2 best solutions below

4
j6t On BEST ANSWER

As you can see in this line:

 * branch                    releases/gcc-13 -> FETCH_HEAD

git fetch didn't store the downloaded branch (named releases/gcc-13 on the remote side) to a "regular" tracking branch on the local side, but to the pseudo-ref FETCH_HEAD. This happened because you gave an explicit branch name on the git fetch command:

git fetch origin releases/gcc-13
                 ^^^^^^^^^^^^^^^ here

The next thing you should do is provide a branch name for the downloaded commits:

git branch releases/gcc-13 FETCH_HEAD

Now you can check out the branch in its own worktree.

git worktree add ../gcc-13 releases/gcc-13

Notable things:

  • The local branch created with git branch is at this point completely unrelated to the remote branch of the same name. They just happen to be the same name and point to the same commit at this time.
  • Using this procedure of not having a local branch right away, is totally normal when you want to do some "sight-seeing" in random branches downloaded from more or less random remote repositories. You are not doing anything wrong.
1
Hamada On
$ git worktree add --track -b <branch> <path> <remote>/<branch>

If is omitted and neither -b nor -B nor --detach used, then, as a convenience, the new worktree is associated with a branch (call it ) named after $(basename ).

If doesn't exist, a new branch based on HEAD is automatically created as if -b was given. If does exist, it will be checked out in the new worktree, if it's not checked out anywhere else, otherwise the command will refuse to create the worktree (unless --force is used).