Appearance
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.1List 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-10The format string
--format accepts %(fieldname) placeholders. These are the most useful:
| Field | What it outputs | Example |
|---|---|---|
%(refname) | Full ref path | refs/heads/feature/login |
%(refname:short) | Short name | feature/login |
%(refname:lstrip=N) | Strip N leading path components | %(refname:lstrip=2) gives feature/login for refs/remotes/origin/feature/login |
%(objectname) | Full SHA | a1b2c3d4e5f6... |
%(objectname:short) | Abbreviated SHA | a1b2c3d |
%(objecttype) | Object type | commit, tag |
%(committerdate), %(creatordate) | Date of the ref or the object it points to | 2024-09-10 14:30:00 -0400 |
%(committerdate:relative), %(creatordate:relative) | Human relative date | 3 weeks ago |
%(committerdate:short), %(creatordate:short) | Short date | 2024-09-10 |
%(authorname) | Author of the pointed-to commit | Alice Smith |
%(subject) | Commit subject line | Add login retry |
%(body) | Commit body | Fixes #123 |
%(contents) | Full commit message | |
%(upstream) | Upstream ref for a branch | refs/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
donePattern 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
donePattern 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"
fiPattern 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
donePerformance notes
git for-each-refreads 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
--countto limit output instead of piping tohead. For a repo with 10,000 refs,--count=5reads only the first 5 sorted refs.
Edge cases
| Situation | Behavior |
|---|---|
| No refs match the pattern | No 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 refs | Handled transparently. No difference from loose refs. |
| Notes refs | Included under refs/notes/. Filter with --exclude=refs/notes/* if unwanted. |
| Worktree HEADs | Each worktree has its own HEAD ref. git for-each-ref on the main repo sees them under refs/worktree/. |
Related commands
| Command | When to use instead |
|---|---|
git branch --list --format | Porcelain for human-readable branch listing. Same format syntax, but adds decorations and coloring by default. |
git tag --list --format | Same for tags. |
git show-ref | List refs with their SHA, one per line. Simpler, no formatting. |
git rev-list --objects --all | Iterate 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]'