Appearance
git rev-parse — The Swiss Army Knife of Git Plumbing
git rev-parse is the most-used plumbing command in CI scripts and the least understood. Most engineers know it for one thing: turning a branch name into a SHA. It does that, plus 40+ other operations that DevOps scripts need every day — parsing revision specifiers, resolving paths, detecting repo state, and emitting structured output for automation.
For a DevOps engineer, mastering git rev-parse means writing CI scripts that handle edge cases (detached HEAD, shallow clones, bare repos, worktrees) without fragile workarounds.
Why a DevOps Engineer Needs This
Every CI pipeline, deployment script, and automation tool needs to answer one or more of these questions:
- "What SHA is checked out right now?" —
git rev-parse HEAD - "Is this a shallow clone?" —
git rev-parse --is-shallow-repository - "Am I inside a Git repo at all?" —
git rev-parse --git-dir - "What branch is this?" (even in detached HEAD) —
git rev-parse --abbrev-ref HEAD - "Is this commit reachable from that branch?" —
git rev-parse --verifywith--quiet - "What's the absolute path of the repo root?" —
git rev-parse --show-toplevel - "Parse this complex revision spec" —
git rev-parse HEAD~3^{/fix:}
A single git rev-parse call replaces git status, git branch, git log, git rev-list, and pwd pipelines — all in one subprocess.
Core Operations
1. SHA resolution (the most common use)
bash
# Resolve any ref to its full SHA
git rev-parse HEAD # current commit
git rev-parse main # branch tip
git rev-parse v2.3.0 # tag
git rev-parse HEAD~5 # 5 commits ago
git rev-parse HEAD^^ # grandparent
git rev-parse HEAD~3^2 # 3rd parent's 2nd parent
git rev-parse :/fixup # commit whose message matches /fixup
git rev-parse :/"Merge pull request" # commit whose message matches string
git rev-parse main..feature # SHA of feature (right side of range)
git rev-parse feature...main # symmetric difference merge base
# Short SHA (unique prefix)
git rev-parse --short HEAD # e.g. a1b2c3d
git rev-parse --short=8 HEAD # exactly 8 chars2. Repo state detection
bash
# Am I inside a Git repo?
git rev-parse --git-dir # prints .git path, exits 0 if in repo
git rev-parse --is-inside-git-dir # true/false
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 2.13+)
# What's the repo root?
git rev-parse --show-toplevel # absolute path of worktree root
git rev-parse --show-cdup # relative path from cwd to root
# Current ref state
git rev-parse --abbrev-ref HEAD # branch name (or HEAD if detached)
git rev-parse --symbolic-full-name HEAD # refs/heads/main or HEAD
git rev-parse --symbolic HEAD # main (short form)3. Revision parsing and validation
bash
# Verify a ref exists (exit code 0/1)
git rev-parse --verify HEAD # exits 1 if no commits
git rev-parse --verify refs/heads/feature-xyz # verify branch exists
git rev-parse --verify --quiet HEAD # no output, just exit code
# Parse complex specs (with error on invalid)
git rev-parse --verify HEAD~3 # exists? fail if not
git rev-parse --verify v2.0.0^{tree} # tag's tree object
# Disambiguate ambiguous refs
git rev-parse --disambiguate abc # find all objects starting with abc4. Path resolution
bash
# Convert relative paths to absolute (within the repo)
git rev-parse --git-path objects # .git/objects path
git rev-parse --git-path refs/heads # .git/refs/heads path
git rev-parse --git-path index # .git/index path
git rev-parse --git-path config # .git/config path
# These work correctly even with:
# - worktrees (.git is a file, not a directory)
# - submodules
# - --git-dir and --work-tree overrides5. Options and flags parsing
bash
# Parse --options in shell scripts (replaces manual getopts for git flags)
git rev-parse --parseopt -- <<'EOF'
help print this help
quiet,-q be quiet
verbose,-v be verbose
branch=! branch name (required)
EOF6. Output formatting for CI
bash
# SHA quality control
git rev-parse --sq HEAD # single-quoted SHA for shell safety
git rev-parse --not HEAD # ^ prefix for negative refspec
# Null-terminated output (safe for arbitrary filenames)
git rev-parse --path-format=absolute --git-path objects # absolute paths
git rev-parse --path-format=relative --git-path objects # relative paths
# All refs matching a prefix
git rev-parse --glob 'refs/heads/release/*' # all release branch SHAs
git rev-parse --branches # all local branch SHAs
git rev-parse --tags # all tag SHAs
git rev-parse --remotes # all remote branch SHAsDevOps Engineering Patterns
1. CI preflight: validate the repo is ready
bash
#!/usr/bin/env bash
set -euo pipefail
# Guard: not a repo
if ! git rev-parse --git-dir >/dev/null 2>&1; then
echo "FAIL: Not inside a Git repository"
exit 1
fi
# Guard: shallow clone won't work for history analysis
if [ "$(git rev-parse --is-shallow-repository)" = "true" ]; then
echo "WARN: Shallow clone detected. Unshallowing for full analysis..."
git fetch --unshallow 2>/dev/null || true
fi
# Guard: bare repo can't run build commands
if [ "$(git rev-parse --is-bare-repository)" = "true" ]; then
echo "FAIL: Bare repository — cannot run workspace build"
exit 1
fi
# Guard: detached HEAD needs special handling for branch-based logic
if [ "$(git rev-parse --abbrev-ref HEAD)" = "HEAD" ]; then
echo "WARN: Detached HEAD — branch name unavailable, using commit SHA"
fi
echo "PASS: Repository preflight checks complete"2. Safe branch name extraction for CI
bash
#!/usr/bin/env bash
set -euo pipefail
# Get the branch name, handling detached HEAD and tag pushes
BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "")
if [ "$BRANCH" = "HEAD" ]; then
# Detached HEAD — try to get the tag or use SHA
TAG=$(git describe --exact-match HEAD 2>/dev/null || true)
if [ -n "$TAG" ]; then
BRANCH="tag/$TAG"
else
BRANCH=$(git rev-parse --short HEAD)
fi
fi
echo "Current branch: $BRANCH"
# Determine deploy environment from branch
case "$BRANCH" in
main|master) ENV="production" ;;
release/*) ENV="staging" ;;
feature/*) ENV="review" ;;
hotfix/*) ENV="hotfix" ;;
*) ENV="development" ;;
esac
echo "Deploy environment: $ENV"3. Resolve complex revision specs in CI
bash
#!/usr/bin/env bash
set -euo pipefail
# Find the merge-base between two refs
MERGE_BASE=$(git rev-parse main...feature 2>/dev/null | cut -f1)
echo "Merge base: $MERGE_BASE"
# Find the previous release tag for changelog generation
PREV_TAG=$(git rev-parse --symbolic-full-name "$(git rev-list --tags --max-count=1 HEAD)")
echo "Previous tag: $PREV_TAG"
# Get the tree SHA of a specific path at a specific revision
TREE_SHA=$(git rev-parse HEAD:src/config.yaml 2>/dev/null || echo "not found")
echo "Config tree SHA: $TREE_SHA"
# Find commits since last tag for version bumping
COMMIT_COUNT=$(git rev-list --count "$(git describe --tags --abbrev=0 2>/dev/null || echo HEAD)..HEAD" 2>/dev/null)
echo "Commits since last tag: $COMMIT_COUNT"4. Git directory path resolution for artifact storage
bash
#!/usr/bin/env bash
set -euo pipefail
# Store build artifacts relative to the Git directory (safe for worktrees)
GIT_DIR=$(git rev-parse --git-dir)
ARTIFACT_DIR="$GIT_DIR/build-artifacts"
mkdir -p "$ARTIFACT_DIR"
# Store SHA + timestamp for deployment tracking
SHA=$(git rev-parse HEAD)
TIMESTAMP=$(date -u +%Y%m%dT%H%M%SZ)
echo "$SHA $TIMESTAMP" > "$ARTIFACT_DIR/deploy-info.txt"
# Get absolute repo root for docker build context
REPO_ROOT=$(git rev-parse --show-toplevel)
docker build -t myapp:"$SHA" "$REPO_ROOT"
# Get relative path from repo root to current directory
CDUP=$(git rev-parse --show-cdup)
echo "Relative from root: ${CDUP:-.}"5. Pre-commit hook: validate branch naming
bash
#!/usr/bin/env bash
# .githooks/pre-commit — validate branch name matches convention
set -euo pipefail
BRANCH=$(git rev-parse --abbrev-ref HEAD)
# Allow main, master, and release branches
case "$BRANCH" in
main|master|HEAD) exit 0 ;;
esac
# Enforce naming convention: type/description or type/ID-description
if ! echo "$BRANCH" | grep -qE '^(feature|fix|hotfix|chore|docs|release|deps)/[a-z0-9._-]+$'; then
echo "ERROR: Branch name '$BRANCH' does not match convention."
echo "Expected: type/description (e.g. feature/add-login, fix/JIRA-1234-timeout)"
exit 1
fi6. CI matrix generation from Git state
bash
#!/usr/bin/env bash
set -euo pipefail
# Generate CI matrix values from repo state
echo "Checking repository state..."
# Determine if this is a PR or direct push
IS_DETACHED=$(git rev-parse --abbrev-ref HEAD)
if [ "$IS_DETACHED" = "HEAD" ]; then
echo "CI_TYPE=pr" # detached HEAD = PR merge commit
else
echo "CI_TYPE=push"
fi
# Get the SHA that started this build (before potential merge)
if [ -n "${GIT_PREVIOUS_COMMIT:-}" ]; then
BASE_SHA=$GIT_PREVIOUS_COMMIT
else
BASE_SHA=$(git rev-parse HEAD^ 2>/dev/null || echo "none")
fi
echo "BASE_SHA=$BASE_SHA"
echo "HEAD_SHA=$(git rev-parse HEAD)"
# Detect monorepo service changes (using pathspec filtering)
CHANGED_DIRS=$(git diff --name-only "$BASE_SHA..HEAD" 2>/dev/null \
| cut -d/ -f1 | sort -u | tr '\n' ',' | sed 's/,$//')
echo "CHANGED_SERVICES=$CHANGED_DIRS"7. Safe shell-quoted SHA for CI variables
bash
#!/usr/bin/env bash
set -euo pipefail
# When passing SHAs through shell variables, quoting is critical
# git rev-parse --sq handles it for you
SHA=$(git rev-parse --sq HEAD)
echo "Safe SHA for eval: $SHA"
# Use in a command safely
eval "echo SHA is $SHA"
# For JSON output in CI, use plain SHA
SHA_PLAIN=$(git rev-parse HEAD)
jq -n --arg sha "$SHA_PLAIN" '{commit: $sha}' > ci-metadata.json8. Detect if a specific commit is an ancestor
bash
#!/usr/bin/env bash
set -euo pipefail
# Check if a fix commit is an ancestor of the current HEAD
FIX_COMMIT="a1b2c3d"
if git rev-parse --verify "$FIX_COMMIT" >/dev/null 2>&1; then
# Check reachability using rev-list (not rev-parse, but complements it)
if git merge-base --is-ancestor "$FIX_COMMIT" HEAD; then
echo "Fix $FIX_COMMIT is already applied"
else
echo "Fix $FIX_COMMIT is NOT yet applied"
fi
else
echo "Fix $FIX_COMMIT does not exist in this repository"
fi9. Parse complex Git revision specs for bisect
bash
#!/usr/bin/env bash
set -euo pipefail
# When bisecting, you often need to parse complex specs
# git rev-parse resolves them all to concrete SHAs
# Resolve a bisect range
BAD=$(git rev-parse --verify HEAD)
GOOD=$(git rev-parse --verify "v2.0.0")
# Resolve a specific file's state at a specific revision
FILE_SHA=$(git rev-parse "HEAD:src/main.go")
# Resolve the first commit on a branch
FIRST=$(git rev-parse --verify "HEAD~$(git rev-list --count HEAD ^main)")
# Resolve a commit by message pattern
MATCH=$(git rev-parse --verify ":/fix memory leak" 2>/dev/null || echo "not found")Exit Code Protocol
| Exit code | Meaning | CI use |
|---|---|---|
| 0 | Success | All normal operations |
| 1 | Not a valid ref, or not in a repo | git rev-parse --verify gates |
| 128 | Fatal error | Broken repository |
Use --quiet to suppress error output when you only care about the exit code:
bash
if git rev-parse --verify --quiet refs/heads/feature-xyz >/dev/null; then
echo "Branch exists"
fiPerformance
git rev-parse is a pure plumbing command — it reads refs and objects directly without touching the working tree. It's one of Git's fastest commands:
| Operation | Typical time |
|---|---|
git rev-parse HEAD | < 1ms |
git rev-parse --git-dir | < 0.5ms |
git rev-parse --verify HEAD~1000 | ~5ms (walking 1000 commits) |
git rev-parse --is-shallow-repository | < 0.5ms |
git rev-parse --show-toplevel | < 1ms |
For CI scripts that call git rev-parse multiple times, batch calls are unnecessary — each call is cheaper than most alternatives.
Common Mistakes
Using
git rev-parse HEADon an empty repo. A repository with zero commits has no HEAD. Checkgit rev-parse --verify HEADfirst, or usegit rev-parse --git-dirto check repo existence.Assuming
--abbrev-ref HEADreturns a branch name. In detached HEAD state it returnsHEAD. Always check:branch=$(git rev-parse --abbrev-ref HEAD); [ "$branch" = "HEAD" ] && branch=""Forgetting
--verifyfor unsafe input. When accepting ref names from user input or CI variables, always usegit rev-parse --verify "$input"to guard against injection or invalid refs.Using
rev-parseinstead ofrev-listfor ranges.git rev-parse A..Breturns only B's SHA. For the list of commits in a range, usegit rev-list A..B.Path resolution with
--git-pathon older Git.--git-pathwas added in Git 2.13. On older versions, usegit rev-parse --git-dirand construct paths manually.
Reference Table
| Task | Command | DevOps value |
|---|---|---|
| Current commit SHA | git rev-parse HEAD | Build stamping, deployment tracking |
| Short SHA | git rev-parse --short HEAD | Readable CI labels |
| Branch name | git rev-parse --abbrev-ref HEAD | Environment routing |
| Full ref name | git rev-parse --symbolic-full-name HEAD | Policy enforcement |
| Repo root | git rev-parse --show-toplevel | Docker context, build paths |
| Git dir path | git rev-parse --git-dir | Artifact storage |
| Inside repo? | git rev-parse --git-dir >/dev/null | CI preflight |
| Is bare repo? | git rev-parse --is-bare-repository | Runner compatibility |
| Is shallow? | git rev-parse --is-shallow-repository | History availability |
| Verify ref exists | git rev-parse --verify ref | Input validation |
| Resolve tree:path | git rev-parse HEAD:path | File-level tracing |
| Resolve commit message | git rev-parse :/pattern | Find-by-message |
| All branch SHAs | git rev-parse --branches | Bulk operations |
| All tag SHAs | git rev-parse --tags | Release audits |
| All remote SHAs | git rev-parse --remotes | Cross-repo checks |
| Shell-safe quoting | git rev-parse --sq HEAD | Safe variable assignment |
| Symmetric diff base | git rev-parse A...B | Merge base resolution |
| Path in git dir | git rev-parse --git-path objects | Internal file access |
| Options parsing | git rev-parse --parseopt | Script argument handling |
Script: scripts/rev-parse-manage.sh — automation wrapper for repo state detection, SHA resolution, and CI preflight checks.