git worktree
- Version
- 2.51
- Since
- 2.5
- Review
- Draft
Summary#
git worktree attaches extra working directories to one repository, each with its own HEAD and index. Use one to work on another branch while leaving unfinished files where they are.
Syntax#
git worktree add -b new-branch ../path start-point
git worktree add ../path existing-branch
git worktree list
git worktree remove ../path
git worktree prune
Example#
(
set -eu
scratch=$(mktemp -d "${TMPDIR:-/tmp}/devlookup-git.XXXXXX")
trap 'rm -rf -- "$scratch"' EXIT
unset GIT_CONFIG_GLOBAL $(git rev-parse --local-env-vars)
export GIT_CONFIG_NOSYSTEM=1 GIT_TEMPLATE_DIR= LC_ALL=C
export HOME="$scratch" XDG_CONFIG_HOME="$scratch" GIT_ATTR_NOSYSTEM=1
export GIT_PAGER=cat GIT_EDITOR=true
git init -q -b trunk "$scratch/main"
cd "$scratch/main"
git config user.name "Reference Example"
git config user.email example@example.invalid
git commit -q --allow-empty -m "Start"
printf 'unfinished\n' > draft.txt
git worktree add -q -b hotfix "$scratch/hotfix" trunk
git -C "$scratch/hotfix" commit -q --allow-empty -m "Patch release"
echo "main: $(git branch --show-current)"
echo "linked: $(git -C "$scratch/hotfix" branch --show-current)"
if ! git switch -q hotfix 2> /dev/null; then echo "hotfix is in use"; fi
echo "worktrees: $(git worktree list | wc -l | tr -d ' ')"
git worktree remove "$scratch/hotfix"
echo "worktrees: $(git worktree list | wc -l | tr -d ' ')"
git log -1 --format=%s hotfix
cat draft.txt
)
Expected output#
main: trunk
linked: hotfix
hotfix is in use
worktrees: 2
worktrees: 1
Patch release
unfinished
Common mistakes#
Deleting a worktree directory by hand leaves its record behind, and Git can still treat the branch as in use. Run git worktree remove instead, or git worktree prune afterwards. Before removing a worktree, inspect it with git status --short --ignored --untracked-files=all. Even a normal removal can delete ignored files. Forced removal can also discard modified or untracked files. Its branch remains available.
Version applicability#
Linked worktrees first appeared in Git 2.5, which described the feature as experimental. Git 2.7 added list. Git 2.17 added remove. On older versions, first check for local changes, then delete the linked directory and run prune.
The complete example requires Git 2.28 or later for git init -b.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0