Git Basics: Working on Two Branches with Worktrees
A worktree gives another branch its own directory. You can leave unfinished changes in one directory and work on another branch without stashing them.
Run these commands in Bash with Git 2.28 or newer installed. Start a fresh temporary repository for this article:
git_practice=$(mktemp -d) || exit
mkdir "$git_practice/repository"
cd "$git_practice/repository" || exit
git init -q -b main
git config user.name 'Practice User'
git config user.email 'practice@example.invalid'
git config commit.gpgsign falseThe identity and signing settings apply only to this repository. Use your own identity in real projects. The temporary files remain afterward. Examples assume default Git settings; if a pager opens, press q to leave it.
Create a second working directory
printf 'port=8080
' > app.conf
git add app.conf
git commit -q -m 'Add application config'
git worktree add -q -b fix-port ../port-fix
printf 'Notes in progress
' > notes.txt
git -C ../port-fix branch --show-current
git branch --show-currentfix-port
main-b creates fix-port from the current commit. ../port-fix is its separate working directory. The untracked notes.txt stays in the original directory. Both worktrees share repository history and branches, but have separate working files and staging areas. Git normally prevents checking out the same branch in two worktrees.
Commit in the other worktree
printf 'port=9090
' > ../port-fix/app.conf
git -C ../port-fix add app.conf
git -C ../port-fix commit -q -m 'Change application port'
cat app.conf
cat ../port-fix/app.conf
git status --shortport=8080
port=9090
?? notes.txtgit -C runs a command in the named directory without changing your shell’s directory. The commit updates fix-port; main still has the original config.
Remove the finished worktree
Before removing a real worktree, check for unfinished and ignored files:
git -C ../port-fix status --short --ignoredgit worktree remove also deletes ignored files, even when normal status looks clean. Review the output and move any files you need outside the worktree before continuing. Do not force removal to bypass Git’s safety checks.
The next command removes the clean port-fix directory. Its committed work remains on fix-port.
git worktree remove ../port-fix
git show fix-port:app.conf
cat notes.txtport=9090
Notes in progressThe branch remains available for review or a later merge. Use git worktree list to inspect worktree paths and their branches; absolute paths and commit IDs vary.
References
Acknowledgements
This post was created with assistance from AI.