git worktrees: how to use them and why you should
Have you ever cloned a repo twice because you wanted to switch branches without messing up the state of your current branch?
git worktree is the best git command you haven't heard of.
From the Git Manual (
git help worktree):
In its simplest form,
git worktree add <path>automatically creates a new branch whose name is the final component of
<path>, which is convenient if you plan to work on a new topic. For instance,
git worktree add ../hotfixcreates new branch
hotfixand checks it out at path
../hotfix. To instead work on an existing branch in a new worktree, use
git worktree add <path> <branch>.
This means you can switch to a different branch without stashing or committing the changes on your current branch.
How does this work in practice?
Before cloning a repo I always create a directory for it first:
> mkdir <repo-name>
Then I clone the repo into a
main subdirectory, to represent the
> cd <repo-name>
> git clone <remote-repo> main
From there I can create additional subdirectories for all the branches I need, and easily
cd between them:
> cd main
> git worktree add ../<cool-feature> <existing-branch-name>
> cd ../<cool-feature>
And when I'm done with a worktree I can remove it (tab completion supported for worktree paths):
> cd ../main
> git worktree remove ../<cool-feature>
You can find additional info in the Git Manual about other useful
git worktree commands, such as:
git worktree list
git worktree move
git worktree lock
With a utility like direnv I can create a
.envrc file in the repo directory I created, making it available to each worktree subdirectory.