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/tagsIn 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
git tag Command: Create Tags in CIgit tag creates and lists tags. Reference for -a annotated tags and -l listing, used to cut releases and disc…
git describe Command: Version Strings in CIgit describe builds a human-readable version from tags. Reference for --tags and --always to derive build ver…
git symbolic-ref Command in CIgit symbolic-ref reads and sets symbolic refs like HEAD. Reference for finding a remote default branch reliab…