Skip to content
LatchkeyLatchkey home

git for-each-ref Command in CI

git for-each-ref iterates over refs and prints them in a fully customizable format.

When you need scriptable, sortable output over tags or branches (more than git tag -l offers), for-each-ref is the plumbing tool. It is ideal for finding the latest release programmatically.

Common flags

  • --sort=<key> - sort by a field, e.g. -creatordate or -version:refname
  • --format=<fmt> - output with placeholders like %(refname:short) and %(objectname)
  • --count=N - limit to the first N refs after sorting
  • --points-at <commit> - only refs that point at the given commit
  • <pattern> - restrict to refs matching a glob (e.g. refs/tags/v*)

Example

shell
# Latest tag plus its SHA, newest first
git for-each-ref --sort=-version:refname --count=1 \
  --format='%(refname:short) %(objectname:short)' refs/tags

In CI

for-each-ref with --sort=-version:refname --count=1 is a precise way to grab the newest release tag and any metadata in one call, avoiding fragile parsing of git tag output. Use --points-at to find which tag (if any) the current commit carries.

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@v4
  with:
    fetch-depth: 0   # history, tags, and git describe all need this

- run: |
    git rev-parse --is-shallow-repository   # expect false
    git rev-parse --abbrev-ref HEAD          # prints HEAD when detached

Key takeaways

  • git for-each-ref gives sorted, custom-formatted ref output for release scripts.
  • --count=1 with version sorting reliably returns the latest tag.
  • --points-at reveals whether the current commit is itself a release.

Frequently asked questions

git for-each-ref Command in CI?
When you need scriptable, sortable output over tags or branches (more than git tag -l offers), for-each-ref is the plumbing tool. It is ideal for finding the latest release programmatically.
In CI?
for-each-ref with --sort=-version:refname --count=1 is a precise way to grab the newest release tag and any metadata in one call, avoiding fragile parsing of git tag output. Use --points-at to find which tag (if any) the current commit carries.

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card