I don't know about you, but my memory isn't the best, coupled with switching 20 times a week between branches, I tend to forget branch names (well the exact name anyway). Then, I have to run the "git branch" command.
The problem is that this gives you all branches and doesn't sort branches by the ones with the most recent activity. So you end up seeing a long list you need to scroll.
GIT flags
Luckily for me, I like to fiddle. So I looked into the GIT docs a bit and discovered:
--sort
If you apply this to the "git branch" command, it will at the very least show you your recent branches at the top.
git branch --sort="-committerdate"
--format
Would also be nice to color highlight and show a date. I want the branch name to be green and the date red.
git branch \
--format="%(color:green)%(refname:short) : %(color:red)%(committerdate:relative)"
Much better now, there are some colors and dates to easily identify when the branch was last edited.
Still, there are too many branches. GIT provides a powerful filtering/formatting tool named "for-each-ref" which we can use to further improve our command.
By using "for-each-ref", we get access to a whole list of flags to format and filter as we loop through refs. One such is --count. As the name would indicate, this flag will limit the number of refs returned, which is perfect to help us get the top 5 recent branches.
Putting it all together:
git for-each-ref --sort="-committerdate" \
--format="%(color:green)%(refname:short) : %(color:red)%(committerdate:relative)" \
--count=5 refs/heads/
Note: we add "refs/heads/" at the end just to prevent the command from showing duplicate branches. Without it, you'll see both remote and local branches which might look like this:
origin/staging
staging
Lazy coders are the best coders 😜
While this command is cool, I'm not gonna type that every time, just too many characters!
Instead, we can add a GIT alias, with an alias you can add your own git command:
"git mycommand"
So a shortcut basically, to add a shortcut simply edit this file:
vi ~/.gitconfig
This is the global GIT config for your Linux user, so any command you place here will become available across all your GIT repositories.
Inside this file you should add:
[alias]
rb = !git for-each-ref --sort=\"-committerdate\" --format=\"%(color:green)%(refname:short) : %(color:red)%(committerdate:relative)\" --count=5 refs/heads/
Note: The "!" simply tells git this is a shell command and needs to escape all double quotes since this is a string.
Next, anytime you want to run this shortcut, simply run:
git rb
Top comments (0)