git for-each-ref: Usage, Options & Common CI Errors
By Kaveh Alemi·Latchkey
git for-each-ref lists branches, tags, and other refs in exactly the format you specify.
When a pipeline needs the latest tag, all branches sorted by date, or refs pointing at a commit, for-each-ref gives stable, parseable output that beats scraping git branch or git tag.
What it does
git for-each-ref walks references matching a pattern and prints each using a custom --format with placeholders like %(refname), %(objectname), and %(creatordate), optionally sorted and filtered.
An empty result usually means the ref pattern did not match (refs/tags/ vs refs/tags/*) or that a shallow/single-branch clone never fetched the refs. Quote glob patterns so the shell does not expand them, and fetch tags (fetch-depth: 0) when you expect them.
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.
.github/workflows/ci.yml
- uses:actions/checkout@v4with:fetch-depth:0 # history, tags, and git describe all need this- run:|git rev-parse --is-shallow-repository # expect falsegit rev-parse --abbrev-ref HEAD # prints HEAD when detached
Frequently asked questions
git for-each-ref: Usage, Options & Common CI Errors?
When a pipeline needs the latest tag, all branches sorted by date, or refs pointing at a commit, for-each-ref gives stable, parseable output that beats scraping git branch or git tag.
What it does?
git for-each-ref walks references matching a pattern and prints each using a custom --format with placeholders like %(refname), %(objectname), and %(creatordate), optionally sorted and filtered.
Common errors in CI?
An empty result usually means the ref pattern did not match (refs/tags/ vs refs/tags/*) or that a shallow/single-branch clone never fetched the refs. Quote glob patterns so the shell does not expand them, and fetch tags (fetch-depth: 0) when you expect them.