Stop Using git checkout
Git 2.23 introduced two commands that replace the two different jobs git checkout used to do: git switch — change or create…
Git worktrees provide a flexible way to work with multiple branches in separate directories.
The basic syntax for creating a new worktree is:
git worktree add <path> <branch>
Important Note: You should run these commands from within your main Git repository directory. This ensures that Git understands the context of your worktree operations.
To check out the branch myotherbranch into a new directory at the same level as your current repository:
git worktree add ../myproject-myotherbranch myotherbranch
Using ../ places the new worktree directory next to your current repository directory, which is often preferred for organization and clarity.
To create a new branch named feature-branch and check it out in a new directory:
git worktree add -b feature-branch ../feature-branch main
This creates a new branch feature-branch based on main and checks it out in the ../feature-branch directory.
git worktree listgit worktree remove <path>git worktree prune[Previous sections remain unchanged]
Use descriptive directory names for your worktrees
Clear naming helps you quickly identify the purpose of each worktree.
Example:
git worktree add ../myproject-feature-login feature-login
git worktree add ../myproject-bugfix-123 bugfix-123
Regularly prune unused worktrees to keep your workspace clean
Pruning removes references to deleted worktrees, preventing clutter.
Example:
# List worktrees to see what exists
git worktree list
# Prune any worktrees that no longer exist on disk
git worktree prune
# List again to confirm cleanup
git worktree list
Be cautious when deleting worktree directories manually
Manually deleting worktree directories without using Git commands can cause reference issues.
Example of proper removal:
# Remove a worktree properly
git worktree remove ../myproject-feature-login
# If the worktree is gone but Git still references it, force prune
git worktree prune --expire now
Consider using ../ to place worktrees alongside your main repository
This keeps all project-related directories at the same level, improving organization.
Example directory structure:
/path/to/
├── myproject (main repository)
├── myproject-feature-login (worktree)
└── myproject-bugfix-123 (worktree)
Use worktrees for long-running features or experiments
Worktrees are ideal for work that might take several days or weeks, allowing you to easily switch contexts.
Example:
# Create a worktree for a long-running feature
git worktree add ../myproject-major-refactor major-refactor
# Create another for an experimental idea
git worktree add -b experiment ../myproject-experiment main
Regularly fetch and update all worktrees
Keep all worktrees up-to-date with remote changes to avoid conflicts.
Example:
# Update main repository
git fetch --all
git pull
# Update each worktree
cd ../myproject-feature-login
git pull
cd ../myproject-bugfix-123
git pull