Review a PR or hotfix production without stashing or disturbing the branch you're in the middle of.
Normally a repository has one working tree, so switching branches means stashing or committing your current state, and long builds or a running dev server get disrupted. `git worktree` lets one repository have several working trees, each with its own branch checked out, in different directories.
git worktree add ../app-hotfix -b hotfix/login origin/mainThat creates folder ../app-hotfix, a new branch hotfix/login from origin/main, and checks it out there. Commits made in either folder go into the same repository, so they are immediately visible from the other; no pushing or fetching between them.
Management commands:
git worktree list: all worktrees, their paths and branches.git worktree remove ../app-hotfix: delete the folder and its metadata (refuses if it has uncommitted changes, unless--force).git worktree prune: clean up metadata for folders you deleted by hand.git worktree add --detach ../tmp v2.3.0: a throwaway checkout of a tag.
Rules and gotchas:
- A branch can be checked out in only one worktree at a time; Git refuses a second, to stop two folders from fighting over the same branch pointer.
- Worktrees share objects, refs, config and stashes, so they are far cheaper than a second clone.
- Each worktree has its own index and
HEAD, and untracked or ignored files such asnode_modulesare per folder, so you may need to reinstall dependencies.
Worktrees are also a natural fit for running several tools or agents on different branches in parallel.
Example
# In ~/src/app, mid-feature with a dev server running
git fetch origin
git worktree add ../app-hotfix -b hotfix/login origin/main
cd ../app-hotfix
# ... fix, commit, push ...
git push -u origin hotfix/login
cd ../app
git worktree list
# /home/me/src/app 5d2e9f1 [feature/search]
# /home/me/src/app-hotfix c81a7d3 [hotfix/login]
git worktree remove ../app-hotfixRemember
- One repository, many checked-out folders, shared objects and refs
- A branch can be checked out in only one worktree at a time
- Remove with git worktree remove, not just rm -rf (or prune afterwards)
Watch out for
- Expecting ignored files like node_modules or .env to exist in the new worktree — each folder has its own.