How Can I Get a List of Git Branches, Ordered by Most Recent Commit?
Better Stack Team
Updated on July 25, 2024
To get a list of Git branches ordered by their most recent commit, you can use the git for-each-ref
command along with sorting options. Here’s a command that will do this for you:
git for-each-ref --sort=-committerdate refs/heads/ --format='%(committerdate:iso8601) %(refname:short)'
Explanation
git for-each-ref
: This command iterates over all refs (branches, tags, etc.) in your repository.-sort=-committerdate
: This option sorts the branches by the commit date in descending order (most recent commit first).refs/heads/
: This specifies that we are only interested in local branches.-format='%(committerdate:iso8601) %(refname:short)'
: This formats the output to show the commit date and the branch name.%(refname:short)
gives the short name of the ref (i.e., the branch name without therefs/heads/
prefix).
Example Output
Running the command above might give you output like this:
2024-06-24 10:15:30 +0000 main
2024-06-23 08:45:12 +0000 feature-xyz
2024-06-22 14:20:50 +0000 bugfix-abc
In this example, main
is the branch with the most recent commit, followed by feature-xyz
and bugfix-abc
.
Optional: Without Commit Dates
If you prefer to see just the branch names without the commit dates, you can simplify the format:
git for-each-ref --sort=-committerdate refs/heads/ --format='%(refname:short)'
This will give you an output like:
main
feature-xyz
bugfix-abc
This command provides a quick and effective way to see your branches ordered by their most recent commit.