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}.

To see the list of previous checkouts:

i=0; while [ $? -eq 0 ]; do i=$((i+1)); echo -n "$i. "; git rev-parse --symbolic-full-name @{-$i} 2> /dev/null; done

This Bash one-liner script is not perfect but it should work for most cases. Note that sometimes the number may skip.

Tip: You can add it to .bashrc as a function.

Leave a Comment