Run these commands in a directory devoted to your project:
mkdir project_foo
cd project_foo
git clone --bare [email protected]: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 = [email protected]:yourorg/project_foo.git
fetch = +refs/heads/*:refs/remotes/origin/*
- Go to the
main
worktree. git pull origin main
cd .. #get out of the main worktree and branch
git worktree add ./my-new-branch #creates a my-new-branch directory, as well as a branch of the same name
- Go the worktree root of the repository (where the
.bare
directory is located) 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
If the local branch isn't tracking the remote branch of the same name, do the following:
cd existing-branch-name
git branch --set-upstream-to=origin/existing-branch-name
In response, you should see the following:
branch 'existing-branch-name' set up to track 'origin/existing-branch-name'
Run git status
to confirm this.
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/