git-for-each-ref - Linux


The git-for-each-ref command iterates over all available Git references (refs), executing a specified command for each. It’s commonly used for identifying, filtering, or modifying Git objects.


git for-each-ref [--format=<format-string>] [--sort=<key>] [--count=<n>]
[<pattern>...] <command>


  • --format=<format-string>: Customize the output format string. The default format is %(refname).
  • --sort=<key>: Sort the references by tag, commit, refname, authordate, or creatordate. The default is none.
  • --count=<n>: Limit the number of references to process.
  • <pattern>: Optional patterns to filter the references.


List all branches and their commits:

git for-each-ref --format='%(refname) %(committerdate:iso8601)' refs/heads/

Find commit hashes containing a specific string:

git for-each-ref --format='%(refname) %(objectname)' | grep '<string>'

Delete all branches except the current one:

git for-each-ref --format='%(refname)' refs/heads/ | grep -v HEAD | xargs git branch -d

Common Issues

  • No output: Ensure that the specified patterns match valid references.
  • Unexpected results: Check the customized format string for errors or inconsistencies.


  • Combine with git filter-branch to perform complex branch modifications.
  • Use with git cat-file to retrieve object metadata or contents.

Related Commands

  • git branch
  • git rev-list
  • git for-each-commit