Skip to content

Instantly share code, notes, and snippets.

@socketbox
Last active March 15, 2024 15:32
Show Gist options
  • Save socketbox/7f2dcc68fda4885f3265e7bf85828b27 to your computer and use it in GitHub Desktop.
Save socketbox/7f2dcc68fda4885f3265e7bf85828b27 to your computer and use it in GitHub Desktop.
Start a new git worktree from an existing branch other than the default

Starting out*

mkdir project_foo
cd project_foo
git clone --bare git@github.com:yourorg/project_foo.git .bare
echo "gitdir: ./.bare" > .git

Now edit .bare/config, adding fetch = +refs/heads/*:refs/remotes/origin/* below [remote "origin"]

[remote "origin"]                               
  url = git@github.com:yourorg/project_foo.git 
  fetch = +refs/heads/*:refs/remotes/origin/*  

Branches

To create a branch and a worktree) that is based off of main:

  1. Go to the main worktree.
  2. git pull origin main
  3. cd .. #get out of the main worktree and branch
  4. git worktree add ./my-new-branch #creates a my-new-branch directory, as well as a branch of the same name

To create a worktree based off of an existing branch present in the local repository

  1. Go the worktree root of the repository (where the .bare directory is located)
  2. git worktree add ./existing-branch-name existing-branch-name

That last command should show you the following (if the local branch is setup to track a remote origin):

Preparing worktree (new branch 'existing-branch-name')                                       
branch 'existing-branch-name' set up to track 'origin/existing-branch-name'.       
HEAD is now at cf5bfce6b creating the foobaz                                                                  

Hints

It might be helpful to first push a locally created branch to the remote and then create a worktree based on that remote rather than attempt to create a worktree on a locally created branch that's not tracking a remote branch.

To add a worktree that's based on a branch other than the default (usually main) and tracks that existing, remote branch: git fetch --all --prune git worktree add --track -b new_worktree_branch ./new_worktree_path remote_name/existing_branch

To add a worktree that exists on a remote but has a slash in the branch name: git fetch --all --prune git worktree add --guess-remote local-dir-name "branch/name-with-slash"

To add a worktree whose branch exists on the remote only:

[2023-06-01 14:51:38]>> git fetch origin dockerfile-updates
From github.com:yourorg/project_foo
 * branch              dockerfile-updates -> FETCH_HEAD
[ main][🅰 ][project_foo]
[2023-06-01 14:52:00]>> git worktree add ./dockerfile-updates FETCH_HEAD 

*Source: https://infrequently.org/2021/07/worktrees-step-by-step/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment