Worktrees & Stashing Context
git worktree
Scenario: You're deep in a feature branch, with a half-built change spread across a dozen files, when a critical hotfix comes in. Stashing and switching would work, but you'd have to stop, stash, switch, fix, switch back, and pop - constantly context-switching your whole editor and terminal state.git worktreeoffers another option: check out a second, separate working directory formainright next to your current one, fix the bug there in its own folder, and never disturb your feature branch's files at all.
git worktree gives you multiple working directories, all backed by the same .git repository, each independently checked out on a different branch at the same time:
$ git worktree add ../hotfix main # new dir ../hotfix checked out on main
$ cd ../hotfix # fix, commit, done
$ git worktree remove ../hotfix # clean up
$ git worktree list # see all worktrees
| Approach | When |
|---|---|
git stash | A quick, brief context switch, staying in the same directory |
git worktree | Working on two branches simultaneously, in two separate folders, with nothing to stash or restore |
Tip: Worktrees share the same underlying .git object store rather than duplicating it, so creating one is cheap and fast - nothing like a full second clone. They're especially handy for running a build or test suite on one branch while you keep coding on another in a separate terminal/editor window.