How Can I Get a List of Git Branches, Ordered by Most Recent Commit?
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.
Make your mark
Join the writer's program
Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.
Write for usBuild on top of Better Stack
Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.
community@betterstack.comor submit a pull request and help us build better products for everyone.
See the full list of amazing projects on github