Marco
Marco

Reputation: 9097

What's the difference between the output from rev-parse and symbolic-ref?

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?

Upvotes: 15

Views: 1847

Answers (1)

Leon
Leon

Reputation: 32484

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

Upvotes: 17

Related Questions