A friendly introduction to Git worktrees
Your repository has exactly one working directory. A worktree is essentially an extra working directory that shares the same Git backend (commits, branches, version history etc). Worktrees are used to quickly switch between in different lines of development without needing to stash in-progress file changes first.
The cheatsheet
Creating a worktree
git worktree add <name> <branch>
<name>: The name of your worktree as well as the filepath where it is located on disk<branch>: The name of the branch you want checked-out in your worktree
If the branch you specify is already in use, you may see this error:
fatal: 'branch' is already used by worktree at…
To fix: Append -b <new-branch-name> to the above command. This instructs Git to create a new branch that your worktree can use.
Switching into your new worktree
cd <name>
Worktrees are just folders on disk, so to access your newly created worktree simply navigate into it’s folder on disk. Navigating into it’s folder also automatically switches you onto that worktree’s branch.
Once inside a worktree, modifying, staging and committing files works as you expect:
git add .
git commit -m "<message>"
Every worktree shares the same Git backend, so the commit you just created is immediately available to all other worktrees.
Listing your worktrees
git worktree list
Shows every worktree, where it lives on disk, and which branch it currently has checked out.
Seeing which branches are locked
git branch
- Branches marked with
+in the output are in use by other worktrees - An
*indicates the branch you’re currently on
Removing a worktree
git worktree remove <name>
Deletes the worktree’s folder and project files, but not the branch it was using. Commits and history are also unaffected.
Going further
- Worktrees are one way to context switch between different lines of development; however, I’d still recommend stashing if you’re new to Git
- Additional worktree tips & gotchas
- Advanced Git users may want to explore bare repos in conjunction with worktrees
- Learn about other helpful tools in LearnGit.io’s utility commands module
