Git Cheat Sheet : For-each-ref

kzankpekzankpe
2 min read

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 branches

    • refs/tags/ list tags

    • refs/remotes/ list remote branches

Use Cases and Examples

  1. List all branches

     git for-each-ref refs/heads/
    

    This command will display the refs for all local branches.

  2. Customizing Output

    Use the --format option 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 full refs/heads/ prefix.

    • %(subject): Shows the commit message.

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

  4. 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:

PlaceholderDescription
%(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.

0
Subscribe to my newsletter

Read articles from kzankpe directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

kzankpe
kzankpe