# git for-each-ref Command in CI

> git for-each-ref lists refs with custom formatting. Reference for --sort, --format, and --count to script over tags and branches in release CI.

Source: https://latchkey.dev/learn/command-reference/git-for-each-ref-command-reference  
Updated: 2026-06-26

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
```

> `git rev-parse --abbrev-ref HEAD` returns the literal string `HEAD` on a detached checkout rather than a branch name. On GitHub Actions read `github.ref_name` instead; the git command cannot know what it was checked out for.

## FAQ

### 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.

---

Latchkey runs CI/CD that repairs its own failures. Agent entry points: https://latchkey.dev/agent.txt, https://latchkey.dev/openapi.json, https://latchkey.dev/llms.txt
