brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: use git worktree to check out two branches at once

Git
~/tips/tip-git-worktree-add

git worktree add ../hotfix hotfix

Checks out a second branch in its own folder without stashing or cloning.

Stashing half your work just to look at another branch always feels a bit silly. There is a built-in way around it.

git worktree add ../hotfix hotfix
git worktree list
git worktree remove ../hotfix

A repository can have more than one working tree, the docs say, so you can check out more than one branch at a time. git worktree add makes a new folder next to your repo, with its own checked out branch. It shares the history and the objects with the main one, so it is not a second clone and does not download anything.

In the example, ../hotfix is the folder and hotfix the branch. If you leave out the branch name, git makes a new branch named after the folder. Do your fix there, commit, and your original folder never noticed. When you are done, git worktree remove deletes the folder again.

The caveat: git will not let you check out the same branch in two worktrees at once, which makes sense. And remove only works on a clean worktree. Untracked files or changes in it make git refuse unless you add --force.

git worktree list shows all of them, so you can find the folders you forgot about.

Further reading: git worktree documentation, On this site: git switch – takes you back to the branch you were just on, On this site: git switch – takes you back to the branch you were on

More Git tips git show-branch main feature git log --stat -5 git merge --no-ff feature -m "Merge feature" git merge --squash feature git merge --abort All Git tips (144) All topics

Link