Skip to content
shellhacks.dev
Git

Show the current branch name

Print the current branch name with git branch --show-current, which prints nothing on a detached HEAD, where rev-parse --abbrev-ref prints the word HEAD.

1 min read
Summarize in AI

A script needs the name of the checked out branch, and the two common commands answer differently when there is none.

Shell
git init -q -b main demo && cd demo
git config user.email [email protected]; git config user.name Demo
git commit -q --allow-empty -m first
git branch --show-current
git rev-parse --abbrev-ref HEAD
git checkout -q --detach
echo "detached: [$(git branch --show-current)]"
git rev-parse --abbrev-ref HEAD
Text
main
main
detached: []
HEAD

git branch --show-current, added in Git 2.22, prints the short name of the current branch or an empty line in a detached state, as the git-branch manual says. That makes [ -z "$(git branch --show-current)" ] a clean test for detached HEAD. The older rev-parse --abbrev-ref HEAD prints the literal word HEAD there, which is easy to mistake for a branch called HEAD.

Before Git 2.22 use git symbolic-ref --short -q HEAD, which exits non-zero on a detached HEAD. In a repository with no commits, rev-parse --abbrev-ref HEAD fails, while --show-current already prints the name of the unborn branch.

Share

More snippets

Git

Show the repository root

Print the root of the working tree with git rev-parse --show-toplevel, from any subdirectory, and cd to it in a script that must run from the top.

1 min read
Git

Check for uncommitted changes in a script

Test for uncommitted changes in a script with git diff --quiet, which exits 1 on a change. Add --cached for staged work, since untracked files never count.

1 min read
Git

List untracked files only

List untracked files only with git ls-files -o --exclude-standard. Without the second option the output includes every ignored build file as well.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.