Git Worktree Guide: Parallel Branches Without Losing Local Changes
Use Git worktree for parallel branches. Learn which state is shared, protect detached commits, remove worktrees safely, and run a 46-check local Git lab.
Git worktree creates additional working directories attached to one repository. Each worktree has its own checked-out files, HEAD and index, while ordinary branch refs, tags, objects and the stash reference are shared. Create a separate branch for each active task, inspect worktree state before cleanup, and retain a branch for any detached commits you want to keep. A worktree isolates checkout state, not the whole development environment.
Leave an unfinished change in place and open another task
You have partly staged a refactor when a separate bug needs investigation. Switching branches in the same directory may require decisions about carrying, committing or stashing those edits. A linked worktree gives the second task a different directory, so the first task can retain its exact staged and unstaged state.
This guide uses a deliberately small repository with one tracked text file. The main worktree holds one staged version and a different working-file version. A feature worktree starts from the committed main branch, makes its own commit and then exercises shared state and cleanup checks. These are original local fixtures, not a production outage reconstruction.
The primary question is what changes when you add a worktree. It is not another copy of every aspect of your machine or a separate remote repository. Understanding that boundary makes it useful for bug fixes, review sessions and side-by-side tests without treating it as a security sandbox.
Separate checkout state from repository state
In the tested fixture, creating the feature worktree produces a clean file containing the committed base text. The unfinished main-worktree edits are not copied into it. Staging in the feature worktree leaves the main index unchanged, and committing on feature leaves main pointing to its original commit.
The same feature commit is immediately addressable from the main directory by its object ID and branch name. A tag created in feature is visible from main as well. That visibility does not update the files checked out in main: a ref becoming available and a working directory changing are separate events.
| State | Relationship between worktrees | Practical consequence |
|---|---|---|
| Tracked working files and untracked files | Separate directory contents | Edits in one directory do not automatically appear in the other |
| HEAD and index | Per-worktree state | Separate checked-out commits and staged changes |
| Ordinary branches, tags and objects | Shared repository state | A commit or ref created in one is visible from the others |
| refs/stash | Shared reference and history | Do not assume stash@{0} belongs to the current directory |
| Repository configuration | Shared by default | A local config write can affect another worktree |
| Ports, databases and external services | Outside Git checkout isolation | Parallel applications still need suitable runtime separation |
Source: Git: repository layout and common versus worktree state ↗
Create the branch and path explicitly
The following command sequence is an adaptation pattern for an existing repository, not an instruction to run it blindly. It assumes main is the intended starting branch, fix-parse is a new branch name, and ../project-fix is an unused sibling path. Review status and the starting revision first. The complete disposable lab later runs equivalent operations without touching an existing project.
Using an explicit starting revision makes the task boundary reviewable. For a branch that already exists and is not checked out elsewhere, omit -b and supply that branch. For a read-only investigation at a specific commit, --detach avoids attaching the new checkout to a branch. Record that choice before you start making commits.
# From the existing repository; adapt branch and path names.
git status --short
git worktree list
git worktree add -b fix-parse ../project-fix main
git -C ../project-fix status --short
git -C ../project-fix branch --show-current
# Edit and test in ../project-fix; stage only intended files there.
# After committing and checking that the directory is clean:
git -C ../project-fix status --short
git worktree remove ../project-fix
# Removing the checkout does not delete the fix-parse branch.Source: Git: worktree add,list,move,lock,remove and repair ↗
A branch already checked out is useful diagnostic information
Our lab attempts to add a second worktree for the already active feature branch. Git rejects it, and the test checks that the requested duplicate directory was not created. The appropriate next step is to inspect the worktree list and identify the existing checkout.
If you need another editable task, create another branch from the desired commit. If you need another view of the same revision, use a detached worktree. Overriding the branch guard removes a useful protection; it does not create independent branch tips with the same name.
Directory names and branch names need not match. Use a naming convention that helps people find the task, but verify with Git rather than inferring the branch from a folder label. In scripts, prefer the documented porcelain listing and parse its records carefully; ordinary display columns are intended for people.
Shared stash means shared ordering, not automatic application
The feature checkout in the fixture temporarily modifies its tracked file and creates a stash. Both worktrees then resolve refs/stash to the same object, and the main worktree can see its message in stash list. No stash is applied to main, so its earlier staged and unstaged edits remain intact.
This is why using stash@{0} as a permanent identifier for a task is fragile when several worktrees are active. Another stash can change the ordering. Inspect messages and contents before an apply or pop, and consider a named branch and commit when a change needs a durable task identity.
A worktree often removes the need to stash merely to start another task. It does not eliminate stash or turn each directory into a private stash namespace. Agree on ownership if several people or automated processes operate on the same repository storage.
Do not confuse --local with per-worktree configuration
The lab writes lab.shared with config --local from feature, then reads the value from main. That demonstrates the default shared repository configuration using an inert example key. A production setting such as a remote URL deserves the same awareness of scope.
To demonstrate an actual per-worktree override, the disposable repository enables extensions.worktreeConfig and assigns separate lab.location values with config --worktree. Effective reads return main-only in one checkout and feature-only in the other. The experiment changes no global configuration.
Enabling this extension in a real repository is a compatibility and migration decision. Review the official instructions, especially existing core.worktree or core.bare settings and the Git versions your tools use. Without the extension, --worktree does not automatically provide the separation its name might suggest. The lab uses a fresh non-bare repository so it does not demonstrate that migration.
Run the complete disposable repository experiment
Save the listing as worktree_lab.py and run python worktree_lab.py without optimization flags. It requires Python and a Git executable on PATH. We executed the exact program on Git 2.51.1 and Python 3.12.14: 46 checks passed across 64 Git commands. It creates a temporary repository, performs no network operations and removes only its generated temporary data at the end.
The subprocess environment removes inherited GIT_ overrides, disables system and global config reads for these commands, and supplies fixture author details. Empty template and hook paths and disabled commit signing make the experiment independent of the author’s personal setup. Those settings are confined to the child commands; they are not recommendations to change a real project’s controls.
The assertions compare original diffs byte for byte, resolve shared commit and stash identities, retain a detached commit with a branch, and exercise move, lock and normal removal. Expected failures are checked through return codes. If an unexpected Git command fails, the program stops rather than interpreting an incomplete run as success.
import os
from pathlib import Path
import subprocess
import tempfile
checks = calls = 0
def check(condition):
global checks
assert condition
checks += 1
with tempfile.TemporaryDirectory(prefix='worktree-lab-') as temp:
root = Path(temp)
main, feature, review = (root / n for n in ('main', 'feature', 'review'))
empty = root / 'empty'
empty.mkdir()
env = {k: v for k, v in os.environ.items() if not k.startswith('GIT_')}
env.update(GIT_CONFIG_NOSYSTEM='1', GIT_CONFIG_GLOBAL=os.devnull,
GIT_TERMINAL_PROMPT='0', GIT_AUTHOR_NAME='Local Lab',
GIT_AUTHOR_EMAIL='lab@example.test', GIT_COMMITTER_NAME='Local Lab',
GIT_COMMITTER_EMAIL='lab@example.test')
def git(where, *args, ok=True):
global calls
calls += 1
result = subprocess.run(['git', '-c', f'core.hooksPath={empty}',
'-c', 'commit.gpgSign=false', '-c', f'init.templateDir={empty}',
'-C', str(where), *args], env=env, text=True, capture_output=True)
if ok and result.returncode:
raise RuntimeError(result.stderr)
return result
def out(where, *args):
return git(where, *args).stdout.strip()
git(root, 'init', '-b', 'main', str(main))
(main / 'note.txt').write_text('base\n')
git(main, 'add', 'note.txt')
git(main, 'commit', '-m', 'base')
base = out(main, 'rev-parse', 'HEAD')
(main / 'note.txt').write_text('main staged\n')
git(main, 'add', 'note.txt')
(main / 'note.txt').write_text('main working\n')
staged = out(main, 'diff', '--cached')
unstaged = out(main, 'diff')
check(bool(staged) and bool(unstaged))
git(main, 'worktree', 'add', '-b', 'feature', str(feature), 'main')
check(out(feature, 'rev-parse', 'HEAD') == base)
check((feature / 'note.txt').read_text() == 'base\n')
check((feature / '.git').is_file())
check(not out(feature, 'status', '--porcelain'))
check(git(main, 'worktree', 'add', str(root / 'duplicate'),
'feature', ok=False).returncode != 0)
check(not (root / 'duplicate').exists())
check(out(main, 'rev-parse', '--git-common-dir') == '.git')
check(Path(out(feature, 'rev-parse', '--git-common-dir')).resolve()
== (main / '.git').resolve())
check(out(main, 'rev-parse', '--git-path', 'index')
!= out(feature, 'rev-parse', '--git-path', 'index'))
(feature / 'note.txt').write_text('feature committed\n')
git(feature, 'add', 'note.txt')
check(out(main, 'diff', '--cached') == staged)
git(feature, 'commit', '-m', 'feature change')
tip = out(feature, 'rev-parse', 'HEAD')
check(tip != base)
check(out(main, 'rev-parse', 'main') == base)
check(out(main, 'rev-parse', 'feature') == tip)
check(out(main, 'cat-file', '-t', tip) == 'commit')
git(feature, 'tag', 'lab-shared')
check(out(main, 'rev-parse', 'lab-shared') == tip)
git(feature, 'config', '--local', 'lab.shared', 'yes')
check(out(main, 'config', '--get', 'lab.shared') == 'yes')
# Enable per-worktree configuration only in this disposable repository.
git(main, 'config', 'extensions.worktreeConfig', 'true')
git(main, 'config', '--worktree', 'lab.location', 'main-only')
git(feature, 'config', '--worktree', 'lab.location', 'feature-only')
check(out(main, 'config', '--get', 'lab.location') == 'main-only')
check(out(feature, 'config', '--get', 'lab.location') == 'feature-only')
(feature / 'note.txt').write_text('temporary feature edit\n')
git(feature, 'stash', 'push', '-m', 'lab shared stash')
stash = out(feature, 'rev-parse', 'refs/stash')
check(out(main, 'rev-parse', 'refs/stash') == stash)
check('lab shared stash' in out(main, 'stash', 'list'))
check(not out(feature, 'status', '--porcelain'))
git(main, 'worktree', 'add', '--detach', str(review), 'feature')
check(out(review, 'rev-parse', 'HEAD') == tip)
check(git(review, 'symbolic-ref', '-q', 'HEAD', ok=False).returncode != 0)
(review / 'review.txt').write_text('keep this experiment\n')
git(review, 'add', 'review.txt')
git(review, 'commit', '-m', 'detached experiment')
detached = out(review, 'rev-parse', 'HEAD')
check(detached != tip)
check(out(main, 'rev-parse', 'feature') == tip)
git(review, 'branch', 'saved-review')
check(out(main, 'rev-parse', 'saved-review') == detached)
check(out(main, 'worktree', 'list', '--porcelain').count('worktree ') == 3)
git(main, 'worktree', 'remove', str(review))
check(not review.exists())
check(out(main, 'rev-parse', 'saved-review') == detached)
(feature / 'note.txt').write_text('dirty\n')
check(git(main, 'worktree', 'remove', str(feature), ok=False).returncode != 0)
check((feature / 'note.txt').read_text() == 'dirty\n')
git(feature, 'restore', 'note.txt') # discard only this known lab edit
(feature / 'untracked.txt').write_text('lab scratch\n')
check(git(main, 'worktree', 'remove', str(feature), ok=False).returncode != 0)
check((feature / 'untracked.txt').exists())
(feature / 'untracked.txt').unlink() # remove only the generated lab file
moved = root / 'feature-moved'
git(main, 'worktree', 'move', str(feature), str(moved))
check(not feature.exists() and moved.exists())
check(out(moved, 'rev-parse', 'HEAD') == tip)
git(main, 'worktree', 'lock', '--reason', 'lab retention', str(moved))
check('locked lab retention' in out(main, 'worktree', 'list', '--porcelain'))
check(git(main, 'worktree', 'remove', str(moved), ok=False).returncode != 0)
check(moved.exists())
git(main, 'worktree', 'unlock', str(moved))
git(main, 'worktree', 'remove', str(moved))
check(not moved.exists())
check(out(main, 'rev-parse', 'feature') == tip)
check(out(main, 'worktree', 'list', '--porcelain').count('worktree ') == 1)
check((main / 'note.txt').read_text() == 'main working\n')
check(out(main, 'diff', '--cached') == staged)
check(out(main, 'diff') == unstaged)
check(out(main, 'rev-parse', 'HEAD') == base)
print(out(main, '--version'))
print(f'PASS: {checks} checks across {calls} Git commands; local fixture only')
Name a detached experiment before removing its checkout
The review worktree starts detached at the feature tip and makes a new commit. The feature branch still points to its earlier commit. The lab then creates saved-review at the detached commit and confirms that the branch still resolves after the review directory is removed.
That distinction matters for experimental fixes: creating a commit does not necessarily advance a branch you expect to retain. Before cleanup, inspect HEAD and create an appropriate branch for work you intend to keep. A filesystem directory is not the durable identity of a change, and removing it should not be your first opportunity to discover that the commit was detached.
Treat cleanup failures as evidence to inspect
The fixture first attempts ordinary removal with a modified tracked file, then with an untracked file. Both attempts fail and the tests confirm the data remains present. It discards only its known generated edits, moves the clean checkout through Git, locks it, verifies removal is refused, then unlocks and removes it normally.
For real work, inspect tracked differences, untracked files and ignored build outputs before removal. Preserve anything valuable through the appropriate commit, backup or task workflow. The lab’s restore and unlink calls concern only invented fixture data; copying them into an existing checkout would be a different operation.
Removing the feature worktree leaves its branch intact in the experiment. Branch retirement is a separate review decision. If a checkout has been moved or deleted outside Git, inspect the recorded paths before choosing repair or pruning. A missing removable drive is not equivalent to an abandoned task; avoid turning a temporary absence into cleanup by assumption.
Plan the runtime boundary as well as the Git boundary
Each checkout may need its own dependencies, generated outputs and editor context. Two application processes can still compete for a port or write to the same database. Decide which services may be shared and which need separate instances before running a second copy of the application.
This local test does not cover submodules, sparse checkout migration, disconnected storage, concurrent writers or Windows filesystem behavior. Worktrees also share underlying repository storage, so they are not independent backups. Use a separate clone when your goal requires a separate repository administration boundary.
For ordinary parallel tasks, the reliable sequence is simple: choose an explicit starting revision, create a distinct branch or deliberate detached checkout, work in the correct directory, inspect shared state before changing it, and retain the intended commit before cleanup. The result is fewer context switches with a clear account of what is actually isolated.
Your next steps
- Use distinct branches for independent active tasks.
- Working files,HEAD and index are separate; ordinary refs and objects are shared.
- Treat stash and default repository configuration as shared state.
- Name detached commits you want to retain before removing the checkout.
- Inspect cleanup failures and runtime dependencies instead of forcing past them.
Sources & official resources
Linked resources checked on 2026-11-02. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →