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?
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 .
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.
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" "$@")"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With