How to get latest commits and branch

Git does not directly store the creation date of a branch, so there's no built-in Git command to list recently created branches in order of their creation. However, you can approximate this using commit information.

git for-each-ref --sort=-committerdate refs/heads/ --format="%(refname:short) - %(committerdate:relative)"

This shows branches by the last commit date. It’s not exact for creation time, but it’s helpful in many cases.

🔍 Step-by-step Breakdown:

1. git for-each-ref

This is a powerful Git plumbing command that lets you iterate over references (branches, tags, remotes, etc.).

2. refs/heads/

This tells Git to only look at local branches. (Remote branches live in refs/remotes/.)

3. --sort=-committerdate

  • Sorts the branches by the last commit date (most recent first).

  • The - prefix means descending order (newest first).

  • If you used committerdate without -, it would show oldest first.

4. --format="%(refname:short) - %(committerdate:relative)"

This formats the output using placeholders:

  • %(refname:short): The branch name without the full refs/heads/ prefix (e.g., just main instead of refs/heads/main).

  • %(committerdate:relative): Shows when the last commit was made on that branch in a human-readable relative form (like "3 days ago").


🔁 Internally:

Git does something like this:

  1. Looks at all local branches.

  2. Finds the latest commit on each.

  3. Sorts them by the committer date of those commits.

  4. Displays the name and how long ago the last commit was.

0
Subscribe to my newsletter

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

Written by

Tushar Mukherjee
Tushar Mukherjee