Git: Output just the current branch name

Train your branches with care.

To print just the name of the current branch, use:

$ git branch --show-current
main

The --show-current option was added in Git 2.22 (2019-06-07), thanks to Daniels Umanovskis in commit 0ecb1fc7269.

The option only ever outputs branch names. In “detached head“ mode, it outputs nothing:

$ git switch -d @~
HEAD is now at b6e126e Smurfing smurfation

$ git branch --show-current

(@ is short for HEAD, the current commit. @~ means the commit before HEAD.)

If you want the current SHA when in detached mode, use:

$ git rev-parse @
b6e126e81cd436d59687bc7ba9371c5fa5c7900f

Boom, that’s it, that’s the post. You can copy that command and go on your merry business.

Below we’ll deconstruct the flaws in some “legacy” commands recommended before --show-current was added.

Legacy rev-parse command

Many pre-2.22 sources reference this alternative:

$ git rev-parse --abbrev-ref HEAD

Unfortunately, this outputs HEAD and fails on a new repository with no commits:

$ git rev-parse --abbrev-ref HEAD
HEAD
fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'

This error also occurs on a new “orphan” branch with no commits.

Also, in detached head mode, it outputs HEAD and exits with success:

$ git switch -d @~
HEAD is now at b6e126e Smurfing smurfation

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

Treating HEAD as a branch name can lead to failures later in your command chain. It’s complicated by the fact that you can create a branch called “head”, with any capitalization other than all-caps.

These flaws were the motivation for git branch --show-current.

Legacy symbolic-ref command

Another legacy command is to use git symbolic-ref with its --short option:

$ git symbolic-ref --short HEAD

This mostly works, but it quits with a fatal error in detached head mode:

$ git switch -d @~
HEAD is now at b6e126e Smurfing smurfation

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

Fin

May you find your current branch with ease,

—Adam


😸😸😸 Check out my new book on using GitHub effectively, Boost Your GitHub DX! 😸😸😸


Subscribe via RSS, Twitter, Mastodon, or email:

One summary email a week, no spam, I pinky promise.

Related posts:

Tags: