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: git switch with a remote branch name creates the local branch for you

Git
~/tips/tip-git-switch-remote-branch-guess

git switch feature/export

Checks out a colleague's branch from the remote with one short command.

To work on a branch that exists on the server but not on your machine, you don’t need -c or --track. Git guesses what you mean, which I like.

git fetch
git switch feature/export

When no local branch with that name exists, but exactly one remote has a branch called feature/export, git switch creates a local branch from it and sets it to track the remote one. You get branch 'feature/export' set up to track 'origin/feature/export' and you’re on it.

The git fetch first matters. Git only knows about remote branches it has fetched, so a branch your colleague pushed five minutes ago isn’t there until you fetch.

If more remotes have a branch with the same name, say origin and upstream in a fork, the guess is ambiguous and git refuses. Then be explicit:

git switch -c feature/export --track upstream/feature/export

Or set checkout.defaultRemote=origin so git always picks that remote when it has to choose.

A typo is the catch here. If the name doesn’t match anything, git doesn’t create a new empty branch, it simply says the reference is invalid. That’s good, but it also means you need to spell it exactly; git branch -r lists the remote branches to copy from.

Further reading: git-switch documentation

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