Skip to content

git rev-parse — Quick Reference ​

SHA resolution ​

bash
git rev-parse HEAD              # current commit
git rev-parse --short HEAD      # short SHA (unique prefix)
git rev-parse main              # branch tip
git rev-parse v2.3.0            # tag
git rev-parse HEAD~3            # 3 commits ago
git rev-parse HEAD^2            # second parent (merge commit)
git rev-parse :/fix             # commit with "fix" in message
git rev-parse HEAD:path/file    # blob SHA of file at revision
git rev-parse main...feature    # symmetric diff merge base

Repo state ​

bash
git rev-parse --git-dir                  # .git path, exit 0 if in repo
git rev-parse --is-inside-work-tree      # true/false
git rev-parse --is-bare-repository       # true/false
git rev-parse --is-shallow-repository    # true/false
git rev-parse --show-toplevel            # absolute repo root
git rev-parse --show-cdup                # relative path from cwd to root
git rev-parse --abbrev-ref HEAD          # branch name (or "HEAD" if detached)
git rev-parse --symbolic-full-name HEAD  # refs/heads/main

Validation ​

bash
git rev-parse --verify HEAD           # exits 1 if no commits
git rev-parse --verify --quiet HEAD   # no output, just exit code
git rev-parse --verify refs/heads/feature-xyz  # verify branch exists

Path resolution ​

bash
git rev-parse --git-path objects      # .git/objects
git rev-parse --git-path index        # .git/index
git rev-parse --git-path config       # .git/config

Bulk refs ​

bash
git rev-parse --branches              # all local branch SHAs
git rev-parse --tags                  # all tag SHAs
git rev-parse --remotes               # all remote branch SHAs
git rev-parse --glob 'refs/heads/release/*'  # pattern match

CI patterns ​

bash
# Preflight guard
git rev-parse --git-dir >/dev/null 2>&1 || exit 1

# Safe branch name (handle detached HEAD)
BRANCH=$(git rev-parse --abbrev-ref HEAD)
[ "$BRANCH" = "HEAD" ] && BRANCH=$(git rev-parse --short HEAD)

# Repo root for Docker context
cd "$(git rev-parse --show-toplevel)"

# Shell-safe SHA
SHA=$(git rev-parse --sq HEAD)

# Verify a ref exists before using it
git rev-parse --verify --quiet "$REF" >/dev/null || exit 1

# Check if shallow (need unshallow for history)
[ "$(git rev-parse --is-shallow-repository)" = "true" ] && git fetch --unshallow

Exit codes ​

CodeMeaning
0Success
1Not a valid ref or not in a repo
128Fatal error

Git Master — Git Reference for Every Skill Level