Skip to content

Instantly share code, notes, and snippets.

@bartdorsey
Last active September 16, 2022 15:24
Show Gist options
  • Save bartdorsey/ddae4800dfc75195c8c798acdd1969e4 to your computer and use it in GitHub Desktop.
Save bartdorsey/ddae4800dfc75195c8c798acdd1969e4 to your computer and use it in GitHub Desktop.
How I use git worktrees

How I use git worktrees

What are git worktrees?

Git worktrees are a special feature of git that lets you checkout branches/commits into a folder.

How is this different that plain 'ol git checkout?

You can check each branch out into a separate folder. This means no more stashing/un-stashing or committing just to work on several branches at once.

Sounds awesome. How do you use them?

I start by creating a new shiny empty folder to hold my project

mkdir my-project

Then I clone down my respository inside that folder into a folder named "main"

cd my-project
git clone git@github.com/username/somerepo.git main

Then go into that folder.

This is a normal repo, we just named it main

Now here's where the magic happens. Say we have a branch named "dev"

git worktree add ../dev dev

This makes a folder up one level from main, containing the checked out copy of the dev branch, and puts it into a folder called dev

You can go into that folder and work as if it's the main repo. The actual .git folder for the repo lives in the main folder, but you can work out of these other folders. These folders are called worktrees

You can list all your worktrees with

git worktree list

And you can remove a worktree when you want to stop working on a branch with

git worktree remove dev

Git is smart here, and won't let you remove a worktree that has uncommitted changes in it.

How do I start a new branch?

Here's how I do it.

git branch new-branch
git worktree add ../new-branch new-branch

I don't use the git checkout -b command anymore, in fact, I never use git checkout or git stash anymore.

Bonus tip: Working with VSCode

I like to make a .workspace file for VSCode and keep that in my project directory, then I add each branch folder to the workspace. This keeps lots of dev tools and extensions in VSCode happy and the git tools in VSCode will even show you all your branches in the sidebar.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment