Is there any way to git checkout previous branch? Is there any way to git checkout previous branch? git git

Is there any way to git checkout previous branch?


From the release notes for 1.6.2

@{-1} is a way to refer to the last branch you were on. This is
accepted not only where an object name is expected, but anywhere a branch name is expected and acts as if you typed the branch name.
E.g. git branch --track mybranch @{-1}, git merge @{-1}, and
git rev-parse --symbolic-full-name @{-1} would work as expected.

and

git checkout - is a shorthand for git checkout @{-1}.


The simplest way of doing this nowadays is:

git checkout -

... which is an alias of:

git checkout @{-1}

git checkout minus

If you want to know more about this, I wrote an entire article about it here: Checkout The Previous Branch In Git.


As @Karl points out and from git checkout manual:

As a special case, the "@{-N}" syntax for the N-th last branch checks out the branch (instead of detaching). You may also specify - which is synonymous with "@{-1}".

So both git checkout - and git checkout @{-1} would work in this case

Closest I believe is using the git reflog and parse the latest moving from branch1 to branch2 and git checkout branch1