0
0
Gitdevops~5 mins

Creating a worktree in Git - Step-by-Step CLI Walkthrough

Choose your learning style9 modes available
Introduction
Sometimes you want to work on different branches of the same project at the same time without switching back and forth. Creating a worktree lets you have multiple working folders linked to one repository, each on its own branch.
When you want to test a new feature on a separate branch without disturbing your current work.
When you need to review or fix bugs on an older branch while continuing new development.
When you want to build or run different versions of your project side by side.
When you want to avoid the time-consuming process of switching branches frequently.
When you want to keep your main working folder clean while experimenting in another folder.
Commands
This command creates a new worktree folder named 'feature-branch' one level up from the current folder. It checks out the 'feature' branch there so you can work on it separately.
Terminal
git worktree add ../feature-branch feature
Expected OutputExpected
Preparing worktree (checking out 'feature') HEAD is now at abcdef1 Commit message on feature branch
This lists the files in the new worktree folder to confirm it has the project files checked out on the 'feature' branch.
Terminal
ls ../feature-branch
Expected OutputExpected
README.md src .gitignore
Shows all the worktrees linked to this repository, including their paths and checked out branches.
Terminal
git worktree list
Expected OutputExpected
/home/user/project abcdef0 [main] /home/user/feature-branch abcdef1 [feature]
Removes the worktree folder 'feature-branch' and unregisters it from the repository when you no longer need it.
Terminal
git worktree remove ../feature-branch
Expected OutputExpected
Deleted worktree ../feature-branch
Key Concept

If you remember nothing else from this pattern, remember: git worktree lets you work on multiple branches at once in separate folders without switching branches.

Common Mistakes
Trying to create a worktree on a branch that does not exist yet.
Git cannot check out a branch that does not exist, so the command fails.
Create the branch first with 'git branch branch-name' or use 'git worktree add -b branch-name path branch-name' to create and check out in one step.
Deleting the worktree folder manually without using 'git worktree remove'.
Git still thinks the worktree exists, causing errors or confusion.
Always remove worktrees with 'git worktree remove path' to unregister them properly.
Summary
Use 'git worktree add path branch' to create a new folder with a separate branch checked out.
Use 'git worktree list' to see all active worktrees linked to your repository.
Use 'git worktree remove path' to cleanly delete a worktree when done.