Search code examples
gitgit-worktree

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


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.


Solution

  • 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.