Git Worktree

A few days ago, during our office knowledge-sharing meeting, someone introduced the git worktree command. It lets you create a new branch parallel to your current working branch so you can start something new — or handle a hotfix — without stashing or committing your unfinished changes.

It turned out to be incredibly useful. With git worktree, you can maintain multiple working directories linked to the same Git repository with almost no friction.


Why use worktrees?

Imagine you're working on a long-running feature — say, an optimization — and suddenly you’re assigned an urgent production bug. Typically, you would stash your changes or make a temporary commit, switch branches, fix the bug, then restore everything. It's annoying and error-prone.

With worktrees, you can directly spin up a parallel working directory:

git worktree add <path>
# Example:
git worktree add ../hotfix

This creates a new linked worktree, associated with your current repository, with its own metadata and branch checkout. Your original work remains untouched.


Removing a worktree

Once you're done with the hotfix (or any task), removing the worktree is just as simple:

git worktree remove <path>

If you delete the directory manually, Git will eventually clean up its administrative files automatically (based on gc.worktreePruneExpire in git-config). You can also remove stale entries explicitly:

git worktree prune

Other useful worktree commands

1. Create a throwaway worktree (detached HEAD)

Perfect for quick experiments:

git worktree add -d <path>

2. Create a worktree for an existing branch

git worktree add <path> <branch>

This checks out the given branch into a new, isolated working directory.


Further reading

To dive deeper into git worktree:

  git help worktree

Cheers!

#Git #TIL #Worktree