Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

git

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?

like image 475
Marco Avatar asked Jul 11 '17 07:07

Marco


People also ask

What is a symbolic ref?

A symbolic ref is a regular file that stores a string that begins with ref: refs/ . For example, your . git/HEAD is a regular file whose contents is ref: refs/heads/master .

What does git rev-parse do?

In --parseopt mode, git rev-parse helps massaging options to bring to shell scripts the same facilities C builtins have. It works as an option normalizer (e.g. splits single switches aggregate values), a bit like getopt(1) does.

What is git rev-parse -- show toplevel?

This can be used to convert arguments to a command run in a subdirectory so that they can still be used after moving to the top-level of the repository. For example: prefix=$(git rev-parse --show-prefix) cd "$(git rev-parse --show-toplevel)" eval "set -- $(git rev-parse --sq --prefix "$prefix" "$@")"


1 Answers

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
like image 125
Leon Avatar answered Sep 20 '22 14:09

Leon