1. Home
  2. Blog
  3. DevOps

DevOps

Git Worktree Explained: Work on Two Branches at Once

Git worktree lets one repository have several working folders, each with a different branch checked out. Fix an urgent bug without stashing your half-finished feature, review a pull request while tests run, or compare two versions side by side. We ran every command (add, list, remove, prune, lock) and recorded the errors you will meet along the way.

9 min read
Git worktree explained: work on two branches at once

Key takeaways

  • Git worktree adds extra working folders to one repository; all of them share the same commits, branches and remotes.
  • git worktree add -b hotfix ../app-hotfix created a new branch and a folder for it in one step.
  • A branch can be checked out in only one worktree at a time; trying again failed with “is already used by worktree”.
  • Deleting a worktree folder by hand left a stale entry marked “prunable” until we ran git worktree prune.

You are halfway through a feature, with files changed everywhere, when an urgent production bug arrives. The usual options are all awkward: commit half-finished work, stash it and hope you remember, or clone the whole repository again. Git worktree offers a cleaner way: a second folder, attached to the same repository, with a different branch checked out. Your feature stays exactly as it is while you fix the bug next door.

We ran every command on Git 2.56.0 in a throwaway repository. Paths in the output are shortened to /work for readability.

What is a git worktree?

Every repository already has one worktree: the folder you cloned, called the main worktree. git worktree add creates linked worktrees, extra folders whose .git entry is a small file pointing back at the main repository’s .git directory. They all read and write the same object database, so a commit made in one is instantly visible in the others, without pushing or fetching.

Why not just stash or clone?

Option Downside
git stash One working folder only; easy to forget or mix up stashes; build caches and editor state are lost when switching
Second clone Copies the whole history again, has its own branches and remotes, needs fetch and push to share commits
Worktree Shares everything except the checked-out files; each folder keeps its own build output and editor windows

Switching branches in place also forces your tools to rebuild and re-index everything. With worktrees, each branch keeps its own folder, so a long test run on one branch does not block coding on another. For background on branches, see our git branch guide.

Our test repository

git init -b main app
cd app
echo "v1" > app.txt; git add .; git commit -m "initial"
git switch -c feature
echo "feature work" >> app.txt; git commit -am "feature in progress"
git switch main

We have main at commit 81608f0 and a feature branch one commit ahead, at 4e6f796.

Adding a worktree with a new branch

git worktree add -b hotfix ../app-hotfix
Preparing worktree (new branch 'hotfix')
HEAD is now at 81608f0 initial

-b hotfix created a new branch starting from the current commit, and ../app-hotfix is the folder to create. Putting worktrees next to the repository, not inside it, keeps them out of git status and your editor’s search. If you leave out -b, Git names the new branch after the last part of the path, so git worktree add ../hotfix would create a branch called hotfix.

Checking out an existing branch

git worktree add ../app-feature feature
Preparing worktree (checking out 'feature')
HEAD is now at 4e6f796 feature in progress

Give the branch name as the second argument to open an existing branch in a new folder. This is how you review a colleague’s branch, or run its tests, without touching your own work. You can also start a new branch from any commit or remote branch: git worktree add -b fix-login ../fix origin/main.

Listing worktrees

git worktree list
/work/app         81608f0 [main]
/work/app-feature 4e6f796 [feature]
/work/app-hotfix  81608f0 [hotfix]

Each line shows the folder, the checked-out commit and the branch. The porcelain format, git worktree list --porcelain, prints the same information in a stable machine-readable layout for scripts.

A branch can be checked out in only one worktree

git worktree add ../again feature
fatal: 'feature' is already used by worktree at '/work/app-feature'

git switch feature          # from the main worktree
fatal: 'feature' is already used by worktree at '/work/app-feature'

Git refuses to check out the same branch in two places, because a commit in one folder would silently change the files the other one expects. This protects you, but it surprises people: once a branch lives in a worktree, you cannot even switch to it in the main folder. Work on it in its own folder, or remove that worktree first. If you only need to look at a branch, use a detached worktree, shown below.

A complete hotfix workflow

cd ../app-hotfix
echo "fix" > fix.txt; git add fix.txt; git commit -m "hotfix: patch"
cd ../app
git log --oneline --all
4e6f796 feature in progress
82531bd hotfix: patch
81608f0 initial
git merge hotfix            # main now contains the fix
ls
app.txt  fix.txt

The commit made in app-hotfix appeared in the main folder’s log immediately, with no push or fetch, because both folders share one repository. We merged it into main, and the feature branch was never touched. In a team you would push the hotfix branch and open a pull request instead; the CI pipeline from our GitHub Actions guide runs exactly as it does for any branch.

Removing a worktree

echo dirty >> ../app-feature/app.txt
git worktree remove ../app-feature
fatal: '../app-feature' contains modified or untracked files, use --force to delete it

git worktree remove --force ../app-feature
removed feature

git worktree remove deletes the folder and Git’s record of it, but only if the worktree is clean. With uncommitted changes, it refused, which is a useful safety net. --force removes it anyway and those changes are lost. The branch itself is not deleted: feature still existed afterwards and could be checked out again. You can never remove the main worktree this way.

Deleting the folder by hand, then pruning

rm -rf ../app-hotfix
git worktree list
/work/app        82531bd [main]
/work/app-hotfix 82531bd [hotfix] prunable

git worktree prune -v
Removing worktrees/app-hotfix: gitdir file points to non-existent location
git worktree list
/work/app 82531bd [main]

Deleting the folder with your file manager leaves Git’s metadata behind, and the list marks the entry as prunable. Until it is pruned, the branch still counts as checked out, so you cannot use it in another worktree. git worktree prune cleans up entries whose folders no longer exist; -n shows what it would remove without doing it. Git also prunes old entries automatically during garbage collection, but running it yourself is instant. Prefer git worktree remove so this never happens.

Detached worktrees for looking around

git worktree add --detach ../review HEAD~1
Preparing worktree (detached HEAD 81608f0)
HEAD is now at 81608f0 initial

--detach checks out a commit without any branch, so it never conflicts with the one-branch rule. It is ideal for comparing behaviour with an older release, running a benchmark against the previous commit, or bisecting a bug while you keep coding.

Locking a worktree

git worktree lock --reason "on USB drive" ../review
git worktree list --porcelain
worktree /work/review
detached
locked on USB drive

git worktree remove ../review
fatal: cannot remove a locked working tree, lock reason: on USB drive
use 'remove -f -f' to override or unlock first

git worktree unlock ../review
git worktree remove ../review     # removed review

A locked worktree is protected from prune, move and remove. That matters for worktrees on removable drives or network shares, which can look missing while unmounted and would otherwise be pruned. Unlock it before removing, or pass -f twice.

What worktrees share, and what they do not

  • Shared: all commits and objects, branches and tags, remotes (see our git remote guide), configuration, and the stash list.
  • Per worktree: the checked-out files, the index (staging area), HEAD, and any in-progress merge, rebase or cherry-pick.
  • Not handled for you: ignored files such as node_modules, virtual environments and .env files. Each new folder needs its own dependencies installed and its own local settings copied.

In our test the main repository’s .git folder was 87 KB, while each linked worktree held only its own checked-out files, so extra worktrees cost far less disk space than extra clones on large repositories.

Tips and folder layouts

  • Use a predictable layout, for example project/ for main and project-wt/branch-name/ for linked worktrees.
  • Give each worktree its own ports and databases if you run two dev servers at once.
  • Clean up regularly with git worktree list and remove; forgotten worktrees keep branches locked.
  • Use worktrees with AI coding agents or parallel tasks: each task gets its own folder and branch, and nothing collides.
  • Submodules are supported but need extra care; Git refuses to remove a worktree containing submodules without --force.

Git worktree cheat sheet

Task Command
New branch in a new folder git worktree add -b name ../path
Existing branch git worktree add ../path branch
Look at a commit git worktree add --detach ../path commit
List git worktree list
Remove git worktree remove ../path
Clean up deleted folders git worktree prune -v
Protect or release git worktree lock / unlock
Move a worktree git worktree move ../old ../new

For the rest of everyday Git, see our Git commands cheat sheet.

Final thoughts

Git worktree removes the friction from context switching. Instead of stashing, committing half-done work or cloning again, add a folder for the new task, do the work there, and remove it when you are finished. Remember the three rules we hit in testing: a branch can live in only one worktree, remove worktrees with Git rather than deleting folders, and lock any worktree on a drive that may disappear. With those habits, working on two or three branches at once becomes routine.

Frequently asked questions

What is git worktree used for?

It gives one repository several working folders, each with its own branch checked out, so you can work on a hotfix, a review and a feature at the same time without stashing or cloning.

Can two worktrees use the same branch?

No. Git refuses to check out a branch that is already used by another worktree. Use a detached worktree if you only need to look at the same commit.

How do I delete a git worktree?

Run git worktree remove with the folder path. If you already deleted the folder by hand, run git worktree prune to clean up the leftover entry.

Does removing a worktree delete the branch?

No. The branch and its commits stay in the repository. Delete the branch separately with git branch if you no longer need it.

Is git worktree better than cloning the repository twice?

Usually yes. Worktrees share one history, branches and remotes, so commits are visible everywhere instantly and no history is copied. A second clone is fully independent, which is only useful when you want that isolation.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Confusion Matrix Explained: Precision, Recall, F1 and Thresholds in Python

Confusion matrix explained with Python: TP, FP, FN, TN, precision, recall, F1, the accuracy trap, threshold choice by cost and…

Read article →
Software Development

API Pagination: Offset vs Cursor vs Keyset, Tested on 1 Million Rows

API pagination explained: offset vs keyset and cursor pagination timed on 1 million rows, duplicates when data changes, the ties…

Read article →
DevOps

Git Submodule Explained: Add, Clone, Update and Remove Safely

Git submodule explained: add, clone, update –init, update –remote, the detached HEAD trap, foreach and clean removal, tested step by…

Read article →
Test Automation

Pytest tmp path Explained: tmp_path, tmp_path_factory and Temp Files

Pytest tmp_path explained: per-test temporary folders, tmp_path_factory for shared files, monkeypatch.chdir, legacy tmpdir, retention and basetemp.

Read article →
Software Testing

Test Case Prioritization: 6 Techniques Compared With APFD

Test case prioritization compared: risk, coverage, cost, history and random orders scored with APFD and time to find all faults…

Read article →
Databases & SQL

Full Text Search in SQL: FTS5, Ranking, Phrases and Speed

Full text search in SQL with SQLite FTS5: MATCH queries, phrases, prefixes, NEAR, stemming, BM25 ranking, snippets, two gotchas and…

Read article →
Databases & SQL

Generated Columns in SQL: Virtual vs Stored, Indexes and Limits

Generated columns in SQL explained: virtual vs stored, automatic updates, write errors, storage cost, indexing, JSON fields and support in…

Read article →
Software Development

Object Freeze in JavaScript: Shallow vs Deep, Seal and const

Object freeze in JavaScript explained: freeze vs seal vs const, strict mode errors, shallow vs deep freeze, frozen arrays, Map…

Read article →
Software Development

Python hashlib: SHA-256, File Hashes, HMAC and Password Hashing

Python hashlib explained: SHA-256 for strings and files, algorithm speeds, why passwords need PBKDF2 or scrypt, safe verification and HMAC…

Read article →
Software Development

Python UUID Explained: uuid1, uuid4, uuid5, uuid7 and Database Keys

Python UUID explained: uuid4, uuid5, uuid1 privacy, time-ordered uuid7, parsing, storage formats and UUIDs as database keys, tested on Python…

Read article →
Artificial Intelligence

Random Forest in Python: Bagging, Feature Sampling and OOB From Scratch

Random forest in Python from scratch: bootstrap sampling, feature sampling, number of trees, out-of-bag evaluation and impurity vs permutation importance.

Read article →
Software Development

MIME Types Explained: Content-Type, nosniff and a Common Types List

MIME types explained and tested in a browser: Content-Type, nosniff, scripts and stylesheets with wrong types, a common MIME types…

Read article →
DevOps

Git Clean Explained: Remove Untracked Files Without Regret

Git clean explained with dry runs: -n, -f, -d, -x, -X, exclusions, paths, nested repositories and interactive mode, plus a…

Read article →
Test Automation

Pytest approx: Comparing Floats With rel, abs and Collections

Pytest approx explained: default tolerances, the near-zero trap, rel and abs, lists and dicts, NaN, NumPy, and how it differs…

Read article →
Software Testing

Accessibility Testing: WCAG Checklist, Automated Tools and Manual Checks

Accessibility testing explained: WCAG basics, an axe-core scan of a broken and a fixed page, what automation missed, contrast checks…

Read article →
Databases & SQL

SQL UNPIVOT: Turn Columns Into Rows, 4 Ways Tested

SQL UNPIVOT explained: turn columns into rows with UNION ALL, CROSS JOIN with CASE, JSON functions or native UNPIVOT, with…

Read article →
Software Development

Intl NumberFormat in JavaScript: Currency, Compact, Percent and Units

Intl.NumberFormat in JavaScript: locales, currency, compact notation, percent, units, rounding, formatToParts, the non-breaking space trap and formatter reuse.

Read article →
Databases & SQL

SQL EXPLAIN Plan: How to Read Query Plans and Fix Slow Queries

SQL EXPLAIN plan explained: read scans, index searches, covering indexes and temporary sorts, with before and after timings for five…

Read article →
Artificial Intelligence

Decision Tree in Python: Gini, Entropy and Overfitting From Scratch

Decision tree in Python from scratch: Gini impurity, entropy, information gain, best splits, readable rules, and how depth and leaf…

Read article →
DevOps

Git Blame Explained: Find Who Changed a Line, and Why

Git blame explained with a real repository: ignore whitespace, line ranges and functions, ignore-revs files for formatting commits, moved code…

Read article →
Test Automation

Pytest Benchmark: Measure Speed and Catch Performance Regressions

Pytest benchmark tutorial: the benchmark fixture, reading results, parametrized and pedantic benchmarks, saving baselines and failing the build on regressions.

Read article →
Software Testing

Defect Density: Formula, Worked Examples and How to Use It

Defect density explained: the formula, a five-module worked example, per KLOC vs per function point, severity weighting, defect removal efficiency…

Read article →
Databases & SQL

Case Insensitive Search in SQL: LOWER, LIKE, COLLATE and Indexes

Case insensitive search in SQL: LOWER, LIKE, COLLATE NOCASE and expression indexes compared with query plans, plus accented letters and…

Read article →
Databases & SQL

ON DELETE CASCADE in SQL: CASCADE vs SET NULL vs RESTRICT

ON DELETE CASCADE in SQL tested: CASCADE vs SET NULL vs RESTRICT, multi-level cascades, the SQLite foreign key pragma, row…

Read article →
Artificial Intelligence

Logistic Regression in Python: Sigmoid, Log Loss and Gradient Descent From Scratch

Logistic regression in Python from scratch: sigmoid, log loss, gradient descent, odds ratios, thresholds, sigmoid overflow and separable data, tested…

Read article →
DevOps

Git Worktree Explained: Work on Two Branches at Once

Git worktree explained: add, list, remove, prune, lock and detached worktrees, a hotfix workflow, and the errors you will hit,…

Read article →
Test Automation

Pytest ini Explained: addopts, markers, testpaths and Precedence

Pytest ini explained: testpaths, addopts, strict markers, xfail_strict, filterwarnings, minversion, config file precedence and command-line overrides, tested.

Read article →
Software Testing

Test Estimation Techniques: WBS, Three Point PERT and Monte Carlo

Test estimation techniques worked through: WBS, three point PERT, total uncertainty, a Monte Carlo check, percentage rules and Wideband Delphi.

Read article →
Artificial Intelligence

Linear Regression in Python: Least Squares From Scratch, With R Squared

Linear regression in Python from scratch: closed form, NumPy least squares and gradient descent, R squared, RMSE, outliers and curved…

Read article →
DevOps

Git Remote Explained: Add, Set-URL, Rename, Remove and Push URLs

Git remote explained: add, set-url, separate push URLs, rename, remove and prune, plus how to avoid leaking tokens in remote…

Read article →
Test Automation

Pytest Mock: mocker.patch, spy, side_effect and autospec Explained

Pytest mock explained: mocker.patch, return_value, side_effect, spy, autospec and PropertyMock, with tested examples for APIs, clocks and retries.

Read article →
Software Testing

System Testing Explained: Types, Process and a Real End-to-End Example

System testing explained: types, entry and exit criteria, the process, and a real end-to-end test suite run against a small…

Read article →
Artificial Intelligence

Naive Bayes Classifier Explained: Build a Spam Filter in Python

Naive Bayes classifier explained by building a spam filter in Python: Bayes rule, the naive assumption, Laplace smoothing, log probabilities…

Read article →
DevOps

Git Branch Explained: Create, Switch, Rename, Delete and Recover

Git branch explained with tested commands: list, create, switch, rename, delete, merged checks, recovering deleted branches, remote tracking and naming.

Read article →
Test Automation

Pytest raises: Testing Exceptions, match and excinfo

Pytest raises explained with tested examples: match regexes, excinfo, custom and chained exceptions, parametrized error cases, pytest.warns and common mistakes.

Read article →
Software Testing

Non Functional Testing: Types, Metrics and a Real Load Test

Non functional testing explained: 10 key types, measurable requirements, latency percentiles and what a small real load test revealed about…

Read article →