git rev-parse in CI: Branch Names in Detached HEAD
git rev-parse turns refs, branch names, and shorthand into the full object IDs Git uses internally.
rev-parse is the workhorse for scripts that need a commit SHA, the current branch name, or the repo root. It powers most CI build-tagging and image-labeling steps.
Common flags
HEAD- resolve the current commit to its full 40-character SHA--short- print an abbreviated (default 7-char) SHA--abbrev-ref HEAD- print the current branch name (or "HEAD" if detached)--show-toplevel- print the absolute path to the repository root--verify <ref>- verify a ref exists and print its SHA, failing if not--is-inside-work-tree- print true when inside a working tree
Example
# Build a short SHA and branch for image tags
SHA="$(git rev-parse --short HEAD)"
BRANCH="$(git rev-parse --abbrev-ref HEAD)"
echo "Building ${BRANCH}@${SHA}"In CI
rev-parse --short HEAD is the canonical way to derive a short commit ID for Docker tags and artifact names. Note that in detached-HEAD checkouts (common in CI) --abbrev-ref HEAD returns "HEAD"; use the platform branch variable when you need the real branch name.
Using this in CI
CI checkouts are shallow and detached by default, which changes the answer this command gives you. Commands that read history, branch names, or tags need the checkout configured for it.
- uses: actions/checkout@v4
with:
fetch-depth: 0 # history, tags, and git describe all need this
- run: |
git rev-parse --is-shallow-repository # expect false
git rev-parse --abbrev-ref HEAD # prints HEAD when detachedKey takeaways
- git rev-parse --short HEAD produces a stable short SHA for tagging artifacts.
- --abbrev-ref HEAD returns "HEAD" in detached checkouts, so prefer CI env vars for branch names.
- --show-toplevel reliably locates the repo root inside scripts.