Git Cheat Sheet : For-each-ref

Git offers commands to manage repository efficiently. Today we will talk about the command git for-each-ref . This command is helpful if you are dealing with multiple branches, tags or refs in your repository and need an advance filtering.
What is git for-each-ref?
The command allows you to iterate over and examine refs in your repository. Refs are pointers to commits and are located in directories like .git/refs/heads (branches) and .git/refs/tags (tags).
Basic Syntax
git for-each-ref [<option>] [<ref-path>]
<option>: Modify the output format<ref-path>: Specify the category of refs to include. For example:refs/heads/list branchesrefs/tags/list tagsrefs/remotes/list remote branches
Use Cases and Examples
List all branches
git for-each-ref refs/heads/This command will display the refs for all local branches.
Customizing Output
Use the
--formatoption to control the output. For instance, to display each branch name along with the last commit message:git for-each-ref refs/heads/ --format="%(refname:short) - %(subject)"%(refname:short): Displays the branch name without the fullrefs/heads/prefix.%(subject): Shows the commit message.
Sort Branches by Date
git for-each-ref refs/heads/ --sort=-committerdate --format="%(refname:short) - %(committerdate)"--sort=-committerdate: Sorts by the committer date in descending order.List Tags with Commit Info
git for-each-ref refs/tags/ --format="Tag: %(refname:short), Commit: %(objectname), Message: %(subject)"%(objectname): Displays the commit ID (hash) associated with the tag.
Formatting Placeholders
Here’s a quick reference for some commonly used placeholders in --format:
| Placeholder | Description |
%(refname) | Full ref name: refs/heads/main |
%(refname:short) | Short ref name : main |
%(objectname) | SHA-1 of the object the ref points to. |
%(authorname) | Author of the commit |
%(authordate) | Date when the commit was authored |
%(subject) | First line of the commit message |
Conclusion
This command is helpful when you need advanced customization or insights into your refs. Instead or relying on git branch or git tag commands, for-each-ref will tailor the output to your exact needs.




