13

I've run into 2 different ways for git to tell me the current branch:

git rev-parse --abbrev-ref HEAD

and

git symbolic-ref --short HEAD

Ehh.. what do both do exactly and when would they differ, if at all?

1 Answer 1

15

They behave differently in detached HEAD state (when there is no current named branch). In such a situation HEAD is not a symbolic ref and git symbolic-ref exits with an error, whereas git rev-parse --abbrev-ref resolves HEAD to itself.

$ git checkout HEAD^
Note: checking out 'HEAD^'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b <new-branch-name>

HEAD is now at bb2d3b1... fix layout with extra newline

$ git symbolic-ref --short HEAD
fatal: ref HEAD is not a symbolic ref

$ git rev-parse --abbrev-ref HEAD
HEAD

You might also want to check out the git command name-rev. git tries its best to figure out which branch you're on, even in a detached state

$ git name-rev --name-only HEAD
master~1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.