DEV Community

Cover image for How view branches sorted by date in specific format and order
AbdlrahmanSaber
AbdlrahmanSaber

Posted on

How view branches sorted by date in specific format and order

This a short tutorial from a git tricks series.

Let's know how we can list all branches sorted by date.

View branch sorted by date

display a list of all local branches and sort them based on the date of their last commit.

# sort desc (-committerdate)
git branch --sort=-committerdate

# sort asc (committerdate)
git branch --sort=-committerdate
Enter fullscreen mode Exit fullscreen mode

If you’d like to make a custom format you can use for-each-ref with --sort option and --format option to write your format.

git for-each-ref --sort='-committerdate' --format='%(refname)%09%(committerdate)' refs/heads
Enter fullscreen mode Exit fullscreen mode

In the above command, I print the refname first then commitdate in --format option the output will be like this

refs/heads/branch_name commitdate
refs/heads/branch_name2 commitdate

# real output
refs/heads/new_design   Wed Apr 20 12:24:21 2022 +0200

refs/heads/design_assets        Wed Apr 20 11:30:30 2022 +0200
Enter fullscreen mode Exit fullscreen mode

If you want to print the date first then refname, the option format will be like this --format='%(committerdate)%09%(refname)%'

Let’s say you don’t want to print refs/heads and want print just the branch name each time, how we can do this? by using sed.

git for-each-ref --sort='-committerdate' --format='%(refname)%09%(committerdate)' refs/heads | sed 's-refs/heads/--'

#output
branch_name commitdate
branch_name2 commitdate

#real output
new_design      Wed Apr 20 12:24:21 2022 +0200

design_assets   Wed Apr 20 11:30:30 2022 +0200
Enter fullscreen mode Exit fullscreen mode

I find these commands incredibly helpful when returning to work from a weekend or just jumping from project to project. Hopefully, you can use these commands too!

If you found this post useful please share it with your friends 😍

Let’s connect on LinkedIn, Twitter

Top comments (0)