Get previous branch name

Viewed 119

I really like git checkout - to move to my previous branch.

But sometimes I only need to know what my previous branch name is. How could I ask Git that?

For example, if git checkout - moves to branch "prev", I want the command to get just "prev".

1 Answers

git checkout - is shorthand for git checkout @{-1} (see here):

You can use the @{-N} syntax to refer to the N-th last branch/commit checked out using "git checkout" operation. You may also specify - which is synonymous to @{-1}.

You can pass this same reference to rev-parse to get the commit or branch in question:

$ git status
On branch master
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean
$ git checkout not-master
Switched to branch 'not-master'
Your branch is up to date with 'origin/not-master'.
$ git rev-parse --symbolic-full-name @{-1}
refs/heads/master
Related