Worktree
You might say
I'm halfway through a feature and an urgent bug just came up. I don't want to clean up my current work first.
Check out another branch in a second working directoryA Git worktree lets one repository have several working directories at the same time. It is useful when a long task must stay open while another branch needs attention. Each worktree has its own checked-out files, but they share the repository history.
When to use it
- Handle an urgent fix without closing current work
- Compare two branches side by side
- Run separate builds from the same repository
- Keep a long-running task open while reviewing another branch
When NOT to use it
- Create worktrees without tracking where they live
- Edit the same generated output from several worktrees
- Delete the directory manually and leave stale metadata
- Use worktrees when simply switching a clean branch is enough
Anatomy
🗄 The same local repository (.git) Shared history and branch references
📁 my-first-pagemainMain working directory
📁 my-first-page-hotfixhotfix/loginadd the directory next to it
The main working directory contains .git; all worktrees share the same set of history and branch references
Commonly used working directory, currently checking out the main branch
Check out another branch through the additional directory created by worktree add
Variants
Add
git worktree add -b hotfix/login ../hotfix main
When you want to open a new branch and working directory from main
List
git worktree list
View the existing working directory and its branches
Remove
git worktree remove ../hotfix
After completing the task and confirming that the directory does not need to be preserved
Typical use cases
Urgent hotfix
$ git worktree add -b hotfix/login ../my-first-page-hotfix main
Preparing worktree (new branch 'hotfix/login')
HEAD is now at a1b2c3d Initial home page
$ ls ..
my-first-page my-first-page-hotfix
The extra working directory shares the same repository history
Parallel feature
📁 my-first-page
main
Homepage changes have not been completed
3 files have not been submitted
3 files have not been submitted
📁 my-first-page-hotfix
hotfix/login
Formal environment login failed
Fix here → Commit → Push
Fix here → Commit → Push
Code review
Window A
Running...
AI is changing the navigation bar
my-first-page-nav · feat/nav
Window B
Running...
AI is changing the pricing page
my-first-page-pricing · feat/pricing
Each one occupies one worktree. After the modification, each will open a PR and do not cover each other
Side-by-side comparison
$ git worktree list
/Users/hu/my-first-page a1b2c3d [main]
/Users/hu/my-first-page-hotfix e5f6a7b [hotfix/login]
$ git worktree remove ../my-first-page-hotfix
$ git worktree list
/Users/hu/my-first-page a1b2c3d [main]
After the repair is completed, the linked working directory has been removed
Further reading