[TIL] git worktree

TIL about git worktree.

It's funny how a tool you use every single day can still surprise you. Git has so many commands tucked away that never come up in the day-to-day add, commit, push, pull loop, and you only stumble onto them when you hit the exact problem they were built for. In my case, that problem was wanting to work on two branches of the same project, side by side, without stashing or juggling a second clone.

The problem

Say I'm on main and need to try out a migration on a separate branch, without losing my current working directory. The instinct is to just copy the folder:

cp -r ramigs.dev ramigs.dev-migration
cd ramigs.dev-migration
git checkout -b migration

That works, but it's not quite right.

Enter git worktree

git worktree add <path> -b <branch-name> is a single git command that does this for you. A few things that make it different from copying the folder yourself:

So the command would look something like:

git worktree add ../ramigs.dev-migration -b migration

Run from the original repo, and that's the entire setup step. Two folders, two branches, one shared history, no copy-pasting required.

The takeaway

I've been using git for almost a decade and still found a command I didn't even know I needed, and how useful it can be. That's the fun part of tools like this — they're deep enough that you never really stop learning them.