Bash tips: easier git branch deleting

Liam Griffin-Jowett
Jul 3, 2017 · 1 min read

I aspire to be a true lazy programmer.

Every repetitive action I try to automate. Every task that doesn’t translate to automation I try to shrink, saving as many keystrokes as possible. Such it is with deleting git branches.

If you use pull requests in your daily coding life, you’ll know about having to clean up unneeded branches after finishing your task and merging the PR. I created a function to make this easier:

function git_branch_delete_like () {
# get all local branches
git for-each-ref --format='%(refname:strip=2)' refs/heads/* | \
# filter for the matching pattern
grep $1 | \
# delete all matching branches
xargs git branch -D
}

The delete like also solves the problem of “Damn I can’t remember the name of my branch, but it was something like fix-terrible-bug". Just do git_branch_delete_like bug. Of course, by putting this in your ~/.bashrc you have autocompletion so you don’t need to type the whole function name out, however I still find it a bit to flow-disrupting to do git_b<TAB>, so I aliased it to gbd.

alias gbd="git_branch_delete_like"

And my branch deleting laziness is complete.

$ gbd bug
Deleted branch fix-super-terrible-bug (was 6dd0640).

Stay lazy.

Edits:

Thanks to Jakub Narębski for pointing me to git plumbing commands
The original command (not recommended) was

git branch -D $(git branch | grep $1) .

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store