skip to content
blog.metters.dev

Git switch to previous branch

/ 2 min read

If you accidentally switch to the wrong Git branch or switch branches too early, it can be helpful to know a shortcut to switch back to the previous branch. Fortunately, such a shortcut exists: -, also known as the hyphen-minus.*

The - option is an abbreviation that quickly switches back to the previous branch. It is an alias for @{-1}, so git switch @{-1} has the same effect.

Terminal window
git switch foo # <-- 1. switching from main to foo
Switched to branch 'foo'
Your branch is up to date with 'origin/foo'.
Terminal window
git switch - # <-- 2. switching back to main
Switched to branch 'main'
Your branch is up to date with 'origin/main'.
Terminal window
git switch @{-1} # <-- 3. switching back to foo
Switched to branch 'foo'
Your branch is up to date with 'origin/foo'.

Where do I use git switch -?

I use this shortcut to simplify repetitive commands, particularly those related to merging or deployment, for example:

package.json
{
"scripts": {
"mergeIntoTest": "git switch test && git merge - && git push && git switch -"
}
}

The one before the previous one

It is also possible to switch to another previously selected branch. For example, the branch that you worked on before the previous one, but you forgot its name, then you can use git switch @{-2}. I have not had to use this yet, but it might prove useful when writing scripts that need to switch between several branches.

Resources

You can use the @{-N} syntax to refer to the N-th last branch/commit switched to using “git switch” or “git checkout” operation. You may also specify - which is synonymous to @{-1}. This is often used to switch quickly between two branches, or to undo a branch switch by mistake.


* It is just the normal minus/dash symbol on your keyboard, but in fact, there are differences between those characters.