Git worktree tips
Worktrees are conceptually simple, but small details can get overlooked. Below are some tips and code snippets that can help reduce worktree friction.
The cheatsheet
Create a worktree with its own branch
git worktree add <path> <start-point> -b <new-branch>
<path>: The relative path of where the worktree will live on disk, which doubles as the name of the worktree<start-point>: Where in Git history the new branch should be anchored-b <new-branch>: The name of the new branch
Worktree creation shorthand
git worktree add <path>
Without the extra arguments, Git anchors the worktree wherever your current branch is pointing, and uses the <path> argument to name that branch as well.
Worktrees as siblings instead of children
git worktree add ../<path>
Since the <path> argument is an actual file path, adding things like ../ is valid. If the above command is run from the root your Git repo, the worktree will be created as a sibling of your repo instead of a child.
fatal: ‘branch’ is already used by worktree at…
Every worktree you create shares the same Git backend, meaning branches may only be checked out in one worktree at a time. If you try to checkout a branch that is already in use by another worktree, you will get this error.
To fix: Append -b <branch-name> to create a new branch for your worktree to use
Remember: ignored files don’t come along
Worktrees only copy your tracked files, so anything in .gitignore won’t be copied over into new worktrees.
Build artifacts (e.g. node_modules) need rebuilding inside each worktree. Additionally, secrets (e.g. .env files) need to be copied manually. Don’t be tempted to commit your secrets to get around this!
Going further
- If you’re new to worktrees, start with worktree basics
- Bare repos are a more advanced way to use worktrees
- Don’t forget about good ol’ stashing
- Interested in other utility commands? Try this LearnGit.io module
