After an operation that moves HEAD
(such as checkout
, reset
, etc.), you can always get the commit ID that HEAD
pointed to before that operation by running, for instance,
git rev-parse @{1}
What I'm interested in, though, is getting the name of the reference (if any) that HEAD
last pointed to. Here's an example that illustrates what I want. Let's say my repo looks as follows:
Then I check out the develop
branch by running
git checkout develop
and end up with
How can I retrieve the information, from my repo's entrails, that HEAD
was pointing at master
, before that last checkout operation?
This answer suggests extracting the name from the reflog with awk
as a possibility; for instance, with
git reflog -1 | awk '{ print $6; exit }'
(thanks to Ed and Etan for their suggestions).
As far as I can tell, that works well enough. It even prints the SHA of the previous commit, in case HEAD
was detached before the last checkout.
However, the OP raises concerns about robustness and backward compatibility in his comment:
I am marking this answer as correct (which it is, technically), for want of a cleaner approach. However, I am not convinced that the string's format being hard-coded into Git's source code is a good thing, as it means it could break unexpectedly (i.e. in a later version of Git).
Are the OP's concerns legitimate? What is the most robust way to do that?