Note

TIL: git switch - takes you back to the last branch

I have typed git checkout main, then git checkout feature/long-branch-name, then git checkout main again for ten years. Today I learned that git has a shortcut for the branch you were on before.

$ git switch -
Switched to branch 'main'

$ git switch -
Switched to branch 'feature/checkout-redesign'

It works like cd - in the shell. A single dash means "the previous one". It also works with the older command, git checkout -.

Why it is useful

Most of the time, you move between two branches: the one you are working on and the one you compare with or merge into. With the dash, you do not type or tab-complete a name at all.

It works in other places too.

$ git merge -        # merge the branch you were on before
$ git rebase -       # rebase onto it
$ git cherry-pick -  # pick its last commit

How it works

Git records every move of HEAD in the reflog. The dash is shorthand for @{-1}, which means "the branch that was checked out one switch ago". You can go further back.

$ git switch @{-2}   # two switches ago
$ git reflog -5      # see the recent moves

While reading the manual, I found two more that I now use every day.

$ git switch -c fix/typo      # create a branch and switch to it
$ git restore --staged file   # unstage a file, without the old reset syntax

switch and restore were added to split the many jobs of checkout into two commands with clearer names. switch changes branches. restore changes files. If you still use checkout for everything, they are worth ten minutes.

💡
Add an alias if you like: git config --global alias.sw switch. Then git sw - is eight characters.

That is the whole note. Ten years, and one dash.

Great! Check your inbox and click the link to confirm.