Skip to content
Latchkey

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.

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.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →