Champ Champ - 1 year ago 118
Git Question

How to find the last branch checked out in git

We can checkout the last branch using

git checkout -
, but is there a way to just find out what was last branch and not check it out?

I already found that I could use:

git reflog | grep -i "checkout: moving"|head -1|cut -d' ' -f6

But I wanted to know if there is a direct simpler command. I am updating the question to reflect this need. Sorry about not being clear enough

Answer Source

Your sample output (as produced by git reflog | ...) makes it sufficiently clear.

The git rev-parse command can be combined with the reference lookup syntax to do this in one go:

$ git rev-parse --symbolic-full-name @{-1}
$ git rev-parse --abbrev-ref @{-1}

Note that the gitrevisions documentation describes the @{-N} syntax. Note as well that if there is no N'th previous branch, rev-parse silently prints nothing at all:

$ git rev-parse --abbrev-ref @{-2} && echo ok || echo fail
$ git rev-parse --abbrev-ref @{-3} && echo ok || echo fail

And, of course, in most places where you might need the name, you can just use the @{-1} syntax directly.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download