Get the current Git branch name
Read the current branch with git branch --show-current or symbolic-ref, and handle detached HEAD correctly in scripts and CI.
Use git branch --show-current on Git 2.22 or later. It prints the branch name without the formatting added by git branch. In a script that must fail when no branch is checked out, use git symbolic-ref --quiet --short HEAD.
Compare the commands
git branch --show-current
# main
git rev-parse --abbrev-ref HEAD
# main
git symbolic-ref --short HEAD
# main
rev-parse is a widely available alternative on older Git versions, but it needs a resolvable HEAD; a newly initialized repository with no commit is a special case. symbolic-ref HEAD without --short prints the full reference, such as refs/heads/main.
Handle detached HEAD explicitly
Checking out a tag or commit can detach HEAD from a branch. In that state:
git branch --show-currentprints nothing and normally succeeds.git rev-parse --abbrev-ref HEADprintsHEAD.git symbolic-ref --quiet --short HEADreturns a nonzero status.
For a local script that should operate only on a named branch:
#!/bin/sh
branch=$(git symbolic-ref --quiet --short HEAD) || {
echo "A checked-out branch is required." >&2
exit 1
}
if [ "$branch" = main ]; then
echo "Choose a feature branch before running this operation." >&2
exit 1
fi
This is useful for local workflow checks and shell prompts. A pre-push hook that protects a remote branch must also inspect the destination refs supplied to the hook: the currently checked-out branch does not determine every ref a push can update.
FAQ
Why not parse git branch with grep?
Its normal output is intended for people and can include markers, colors, and worktree information. A dedicated output option avoids depending on that presentation.
Why is there no branch name in CI?
Many runners check out a commit directly. Use the CI platform's event-aware metadata when you need the triggering ref. For example, GitHub Actions exposes GITHUB_REF_NAME, and GitLab exposes CI_COMMIT_REF_NAME; these may represent tags or special event refs rather than an ordinary source branch. For pull requests, check the platform's source-branch variable and the event type.
Can several branches contain the checked-out commit?
Yes. Finding branches that contain a commit is a different question from finding the branch currently attached to HEAD.
See git-branch, git-symbolic-ref, GitHub Actions variables, and GitLab predefined variables.
Contact us
Join the community
to join the community
Try Guance
Start online and pay only for what you use.
Get startedChoose a Guance plan