Skip to content

Git For-Each-Ref: Scripting Over References ​

git for-each-ref iterates over branches, tags, and other refs, outputting formatted fields for each one. It is the plumbing alternative to git branch --list, git tag --list, and shell loops over .git/refs/. It works with packed refs, supports arbitrary sort keys, and its --format string lets you emit exactly the fields a script needs.

When to use it ​

  • CI scripts that need to enumerate branches matching a pattern.
  • Release tooling that reads the latest tag per release line.
  • Maintenance automation that checks branch age, stale refs, or ahead/behind counts.
  • Hooks that enforce naming conventions on new refs.

Basic syntax ​

bash
git for-each-ref [--sort=<key>] [--format=<format>] [--count=<n>] [<pattern>...]

Patterns are refname globs. Omitting the pattern iterates all refs under refs/.

List all branches ​

bash
git for-each-ref --format="%(refname:short)" refs/heads/
main
feature/login
release/v2.1

List all tags with dates ​

bash
git for-each-ref --format="%(refname:short) %(creatordate:short)" refs/tags/
v1.0 2024-01-15
v2.0 2024-06-01
v2.1 2024-09-10

The format string ​

--format accepts %(fieldname) placeholders. These are the most useful:

FieldWhat it outputsExample
%(refname)Full ref pathrefs/heads/feature/login
%(refname:short)Short namefeature/login
%(refname:lstrip=N)Strip N leading path components%(refname:lstrip=2) gives feature/login for refs/remotes/origin/feature/login
%(objectname)Full SHAa1b2c3d4e5f6...
%(objectname:short)Abbreviated SHAa1b2c3d
%(objecttype)Object typecommit, tag
%(committerdate), %(creatordate)Date of the ref or the object it points to2024-09-10 14:30:00 -0400
%(committerdate:relative), %(creatordate:relative)Human relative date3 weeks ago
%(committerdate:short), %(creatordate:short)Short date2024-09-10
%(authorname)Author of the pointed-to commitAlice Smith
%(subject)Commit subject lineAdd login retry
%(body)Commit bodyFixes #123
%(contents)Full commit message
%(upstream)Upstream ref for a branchrefs/remotes/origin/main
%(upstream:track)Ahead/behind tracking[ahead 2, behind 1]
%(upstream:track,nobracket)Raw ahead/behind+2 -1
(color:<color>)Color inline%(color:red)%(refname:short)%(color:reset)

Sorting ​

Sort by any field. Prefix with - for descending:

bash
# Most recently committed branches first
git for-each-ref --sort=-committerdate refs/heads/

# Tags sorted by version (lexicographic, not semantic)
git for-each-ref --sort=-creatordate refs/tags/

Multiple sort keys are applied left to right:

bash
git for-each-ref --sort=-committerdate --sort=refname refs/heads/

Real CI/CD patterns ​

Pattern 1: find stale branches for cleanup ​

bash
#!/bin/sh
stale_cutoff=$(date -d "90 days ago" +%s)

git for-each-ref --format="%(refname:short) %(committerdate:unix)" refs/heads/ |
while read -r ref ts; do
  if [ "$ts" -lt "$stale_cutoff" ]; then
    echo "STALE: $ref (last commit $(date -d @"$ts" '+%Y-%m-%d'))"
  fi
done

Pattern 2: enforce branch naming convention in a hook ​

bash
#!/bin/sh
# pre-receive hook: reject branches that do not match pattern
zero="0000000000000000000000000000000000000000"

while read oldrev newrev refname; do
  branch=$(echo "$refname" | sed 's|refs/heads/||')
  case "$branch" in
    main|release/*|feature/*|hotfix/*) ;;
    *)
      echo "ERROR: branch '$branch' does not match naming convention."
      echo "Allowed: main, release/*, feature/*, hotfix/*"
      exit 1
      ;;
  esac
done

Pattern 3: build a changelog from tags between releases ​

bash
#!/bin/sh
last_tag=$(git for-each-ref --sort=-creatordate --count=1 --format="%(refname:short)" refs/tags/)
prev_tag=$(git for-each-ref --sort=-creatordate --count=1 --skip=1 --format="%(refname:short)" refs/tags/)

if [ -n "$last_tag" ] && [ -n "$prev_tag" ]; then
  git log --oneline "$prev_tag".."$last_tag"
fi

Pattern 4: check ahead/behind for all feature branches ​

bash
git for-each-ref --format="%(refname:short) %(upstream:track,nobracket)" refs/heads/ |
while read -r branch track; do
  if [ -n "$track" ]; then
    ahead=$(echo "$track" | cut -d' ' -f1 | tr -d '+')
    behind=$(echo "$track" | cut -d' ' -f2 | tr -d '-')
    echo "$branch: ahead $ahead, behind $behind"
  fi
done

Performance notes ​

  • git for-each-ref reads from packed-refs and loose refs. It does not touch the object database unless you request object fields (%(authorname), %(subject), etc.). Requesting object fields triggers a lookup per ref.
  • Filter by pattern early: refs/heads/release/* is faster than iterating all refs and grepping the output.
  • Use --count to limit output instead of piping to head. For a repo with 10,000 refs, --count=5 reads only the first 5 sorted refs.

Edge cases ​

SituationBehavior
No refs match the patternNo output, exit code 0.
Symrefs (like HEAD)Iterated only if pattern matches refs/*. HEAD in the root namespace is excluded.
Broken ref (file exists but points to a missing object)Error on that ref. Other refs still print.
Packed refsHandled transparently. No difference from loose refs.
Notes refsIncluded under refs/notes/. Filter with --exclude=refs/notes/* if unwanted.
Worktree HEADsEach worktree has its own HEAD ref. git for-each-ref on the main repo sees them under refs/worktree/.
CommandWhen to use instead
git branch --list --formatPorcelain for human-readable branch listing. Same format syntax, but adds decorations and coloring by default.
git tag --list --formatSame for tags.
git show-refList refs with their SHA, one per line. Simpler, no formatting.
git rev-list --objects --allIterate all objects reachable from all refs. Different use case entirely (object enumeration).

Quick reference ​

bash
# All refs, short names
git for-each-ref --format="%(refname:short)"

# Branches only
git for-each-ref --format="%(refname:short)" refs/heads/

# Branches sorted by last commit date
git for-each-ref --sort=-committerdate --format="%(refname:short) %(committerdate:short)" refs/heads/

# Tags with creator date
git for-each-ref --sort=-creatordate --format="%(refname:short) %(creatordate:short)" refs/tags/

# Branches with ahead/behind tracking
git for-each-ref --format="%(refname:short) %(upstream:track)" refs/heads/

# JSON output (Git 2.38+)
git for-each-ref --format="%(refname:short)" --sort=-committerdate refs/heads/ | jq -R -s 'split("\n")[:-1]'

Git Master — Git Reference for Every Skill Level