Sub topic 1
Working on Several Branches at Once with `git worktree`
Prerequisites
You should know how to commit, create and switch branches, and use git fetch. You should also understand the difference between a working directory, the index, and repository history. This chapter assumes command-line Git use.
The problem: one repository, one checked-out branch
A normal Git clone has one working directory. That directory can have only one branch checked out at a time. Switching from main to a feature branch changes the files in that directory.
This becomes inconvenient when unfinished work is present. You might need to stash it before reviewing another branch, or interrupt a long build before fixing an urgent bug. A second clone solves the directory problem, but it downloads another copy of the repository history.
A linked worktree is another working directory connected to the same local repository. Each worktree can have its own checked-out branch, while the repository objects and history remain shared.
Creating your first linked worktree
From the existing repository, create a sibling directory and a new branch with one command:
git worktree add ../myproject-hotfix -b hotfix/login-crash mainGit creates ../myproject-hotfix, creates hotfix/login-crash from main, and checks out that branch there. Your original directory remains on its current branch, so you can continue your existing work without stashing.
To use an existing branch, provide its path and branch name:
git worktree add ../myproject-feature feature/searchWhy a branch can be checked out only once
Git normally prevents the same branch from being checked out in two worktrees. The branch has one checkout state, including its HEAD, index, and working files. Allowing two worktrees to update that state independently would make commits and branch movement ambiguous.
If feature/search is already checked out elsewhere, the second git worktree add fails. Work in the existing worktree, create a new branch, or use a detached worktree for read-only inspection.
Seeing what worktrees exist
List paths, branches, and commits with:
git worktree listFor script-friendly output, use:
git worktree list --porcelainThe list helps you find which worktree owns a branch before switching or removing anything.
Exercise
You need to inspect feature/search while keeping uncommitted changes on main. What command creates a separate worktree for the existing branch?
Show answer
git worktree add ../myproject-feature feature/search