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: