Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 78 ยท Remotes and Collaboration

Worktrees and Multiple Working Directories

Use git worktree to check out several branches in separate folders sharing one repository: add, list, remove, hotfix mid-feature, locking, and worktrees versus clones and stash.

You are halfway through a feature. Your files are a mess, nothing compiles, and a message arrives: production is broken, fix it now. The classic answers are unpleasant. You can commit half-finished work, stash it, or clone the repository a second time. Each works, and each has a cost. There is a better tool: git worktree, which gives one repository several working directories, each with its own branch checked out, all sharing the same history and objects.

By the end of this lesson you will know how to add, list, move, lock and remove worktrees, what the rules are (one branch per worktree), and when a worktree beats a stash or a second clone. Everything runs in the sandbox, because worktrees are purely local.

The idea: one repository, many working trees

Normally a repository has one working tree: the folder next to .git. Whatever branch is checked out there is what you see. Switching branches rewrites your files, which is why you cannot have two branches open at once.

A linked worktree is an extra folder, created anywhere you like, that is connected to the original repository (the main worktree). Each worktree has its own checked-out branch, its own index and its own HEAD, but they share the object database, the branches, the tags and the remotes. A commit made in one worktree is immediately visible to all others, with no pushing or fetching.

TEXT
   ~/work/shop             (main worktree, branch: feature)   .git/  <- the one real repository
   ~/work/shop-hotfix      (linked worktree, branch: hotfix)  .git   <- a small file pointing back
   ~/work/shop-review      (linked worktree, detached HEAD)   .git   <- ditto

Creating and listing worktrees

git worktree add <path> [<branch>] creates a folder and checks out a branch in it. With -b <new-branch> it creates the branch at the same time, starting from the current commit (or from a start point you name).

Bash git worktree add and list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

git worktree list first showed only the main worktree (shop, branch main) and after the add also shop-hotfix [hotfix]. The new folder contains a file named .git, whose single line begins with gitdir: and names the private area shop/.git/worktrees/shop-hotfix in the main repository. That private area holds the things that must be separate per worktree: its HEAD (ref: refs/heads/hotfix) and its index. Everything else is shared. The commit "Fix crash" made in shop-hotfix appeared in git log hotfix of the main worktree immediately.

The final two commands show the one important rule. git switch hotfix from the main worktree failed with fatal: 'hotfix' is already used by worktree at 'shop-hotfix', and in git branch -vv the + sign in front of hotfix marks "checked out in another worktree". Git forbids a branch in two worktrees because a commit made in one would make the other's files and index silently wrong.

You can put the linked folder anywhere, but a sibling of the main folder (../shop-hotfix) is the usual choice. Do not put a worktree inside the main working tree, because the outer repository would see it as untracked files.

The hotfix scenario

This is the situation worktrees were made for: you are in the middle of a feature with uncommitted changes, and you must fix main right now.

Bash A hotfix while the feature is half done

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

No commit, no stash, no branch switch: shop kept its uncommitted line in f.txt ( M f.txt both before and after) while the hotfix was written and committed in shop-main. The graph shows Hotfix on main and Feature half done as two branches from Start. When you are done, git worktree remove ../shop-main deletes the extra folder and its bookkeeping; the commit and the main branch stay in the repository, so the list is back to a single worktree.

In a real project the hotfix folder needs its own dependencies installed (npm install, composer install) and its own build output, which is the main cost of worktrees. In exchange, long builds, test runs and dev servers in one worktree are not disturbed by what you do in another.

Rules and clean-up

Bash Safety rules: duplicates, dirty folders, prune

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The first add of topic was refused (fatal: 'topic' is already used by worktree at '<dir>/w2'). With --detach you may check out any commit, even one a branch points to, which is perfect for reviewing or building a tag without touching branches. Removing a folder that has uncommitted or untracked files needs --force; Git protects you from losing work. And if somebody deletes a worktree folder with rm -rf, the main repository still lists it (the count stayed at 2) until git worktree prune removes the stale record (gitdir file points to non-existent location). That is why you should always use git worktree remove. The branch topic survives the removal of its worktree, as git branch shows.

Lock and move

Worktrees on removable drives or network shares would be pruned automatically when the path disappears. git worktree lock prevents that and, as a bonus, prevents accidental removal; git worktree move relocates a worktree safely.

Bash Locking and moving worktrees

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The listing now shows renamed [a] (moved) and b [b] locked. Removing the locked worktree failed with fatal: cannot remove a locked working tree, lock reason: on a USB drive; after unlock it worked. (The awk call just trims the long absolute paths to their last component so the output stays short.)

Worktrees, clones and stash compared

Stash Second clone Worktree
Setup cost none full download or copy of the history seconds, no extra history
Disk use tiny whole repository again only the extra working files
Both branches usable at once no yes yes
Commits visible to the other copy n/a after push and fetch immediately
Risk forgotten stashes, conflicts on pop copies drift apart one branch per worktree rule; stale folders

Use a stash (Stashing Work in Progress) for a very short interruption when you will come right back. Use a worktree when you need two or more branches in parallel for more than a few minutes: hotfix while mid-feature, reviewing a colleague's pull request without disturbing your files (Pull Requests and Code Review), comparing behaviour of two versions, running a long test suite on one branch while you code on another, or building a release from a tag. Use a separate clone when you need real isolation (different remotes or settings, different repository ownership) or the work should not share anything.

Limitations and good habits

  • One branch per worktree, as seen. Use --detach or -b with a new name.
  • Worktrees share the repository's configuration (.git/config), hooks and stash. Settings that must differ per worktree can use git config --worktree after enabling extensions.worktreeConfig.
  • Submodules in linked worktrees are poorly supported; each worktree needs its own git submodule update --init, and Git warns that the feature is incomplete (Submodules, Subtrees and Monorepos).
  • Tools (IDEs, build caches, node_modules) are per folder. Opening each worktree as its own project is normal.
  • Clean up with git worktree remove, not rm -rf, and run git worktree prune if you did delete one. git gc also prunes records of missing worktrees after a while.
  • Bare repository + worktrees layout: some people keep a bare clone (git clone --bare url project.git) and create one worktree per branch beside it, never having a "main" working folder at all. It is read-only advice here: git worktree add ../main main from inside the bare repository does it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What do all worktrees of one repository share?

    Each worktree has its own HEAD, index and files, but the history (objects), branches, tags and configuration are shared, so commits are visible everywhere at once.
  2. 2. You run git switch hotfix in the main worktree while hotfix is checked out in ../shop-hotfix. What happens?

    A branch can be checked out in only one worktree, to keep each worktree's files and index consistent with its branch.
  3. 3. Which is the right way to get rid of a linked worktree you no longer need?

    git worktree remove deletes the folder and its administrative data. If a folder was deleted by hand, git worktree prune removes the stale record.
  4. 4. When is a worktree clearly better than git stash?

    A stash only parks changes; a worktree gives you a second, ready-to-use working directory while your first one stays exactly as it was.
  5. 5. How can you check out any commit or tag in a new worktree even if a branch pointing to it is already checked out elsewhere?

    A detached HEAD is not a branch, so the one-branch-per-worktree rule does not apply.

Summary

  • git worktree add <path> [-b <branch>] creates another working directory that shares the repository; list, move, lock, unlock, remove and prune manage them.
  • Each worktree has its own HEAD, index and files; objects, branches, tags and config are shared, so commits show up everywhere immediately.
  • A branch can be checked out in only one worktree; use --detach for read-only looks at any commit.
  • The hotfix-mid-feature case needs no commit, stash or branch switch: add a worktree, fix, remove it.
  • Remove with git worktree remove (it refuses dirty folders without --force); git worktree prune cleans up records of folders deleted by hand.
  • Prefer a stash for brief interruptions, a worktree for parallel work, and a clone for real isolation.

Next: Git Objects: Blobs, Trees, Commits and Tags