|home| |posts| |projects| |cv| |bookmarks| |github|

Git Workflow With Worktrees

Sometimes you need to work on two different branches at the same time.

For this, you can use git worktrees.

Demo

Assumming you are in a git repository named repo, one way to create a worktree is this:

git worktree add ../repo-some_suffix -b some_branch_name

This will create a separate copy of the current branch in the folder name ../repo-some_suffix and the new branch is named some_branch_name.

-b some_branch_name can be omitted and then the new branch will be named the same as the new directory, i.e. repo-some_suffix.

If you don't want a worktree for the current branch but for an existing branch, do this:

git worktree add ../repo-some_suffix some_branch_name

Or for an remote branch:

git worktree add ../repo-some_suffix -b some_branch_name origin/some_branch_name

Why I choose ../repo-some_suffix as the worktree path?

My habit is to name the worktree using the repository name and adding some short unique suffix based on the new branch and place the worktree at the same filesystem level as the main worktree.

This makes it easier to track all the worktrees for a repository since they all are at the same path and they have the same name prefix.

To see a list of your current worktrees:

git worktree list

To remove the worktree:

git worktree remove ../repo_foo

You may have to --force remove it(or -f for short).