When using Git, sometimes (often) I find myself forgetting to delete local branches after merging them. To resolve this, it would be great to have a command to delete branches that have been merged into the current branch. The following does the trick.
git branch --merged | grep -Ev "(^\*|^\s+master$)" | xargs git branch -d
How does this work?
Get Merged Branches
git branch --merged
Returns all of the branches that have been merged with our current branch, e.g.
$ git branch --merged already-merged-1 already-merged-2 * develop master
Remove Current Branch and Master Branch
We use the results above with grep to filter our results.
grep -Ev "(^\*|^\s+master$)"
removes any lines that start with
* or where the branch name is “master”. We do not want to remove the current branch (marked with
*) nor the
E sets grep to use “extended regular expression” interpretation and
v indicates “Invert Match”
Extended Regular Expression
Generally when using regular expressions, meta characters (e.g.
|) have special meanings. By default in grep, these special meanings are ignored. By using grep’s Extended Regular Expression feature, these characters have the same special meanings that are usually associated with regular expressions.
By default, grep returns the lines that match the given pattern. In these case, we want to return the lines, which do NOT match the pattern.
$ git branch --merged | grep -Ev "(^\*|^\s+master$)" already-merged-1 already-merged-2
Delete Merged Branches
Now that we have our list of merged branches, we want to run
git branch -d for each branch. We do this using the xargs command.
We pass our results (our two branches listed above) into
xargs git branch -d, which then runs the command for each line in the results.
$ git branch --merged | grep -Ev "(^\*|^\s+master$)" | xargs git branch -d Deleted branch already-merged-1 (was 927613f). Deleted branch already-merged-2 (was 927613f).
is the same as running
$ git branch -d already-merged-1 Deleted branch already-merged-1 (was 927613f). $ git branch -d already-merged-2 Deleted branch already-merged-2 (was 927613f).
The Easy Way
It would be nice to have a Git command to perform this (something like
git branch-delete-merged). We can define this command by running the following from the command line.
git config --global alias.branch-delete-merged '!git branch --merged | grep -Ev "(^\*|^\s+master$)" | xargs git branch -d'
This adds an entry to our Git global configuration, which allows us to run
My Git Configuration
My Iron Code Git Enhancements includes this and other Git aliases and configurations that help me speed up my development workflow.
Inspired by this tweet
Add this to your .bash_profile and thank me later.
alias gcmb="git branch –merged | grep -Ev '(^*|master)' | xargs git branch -d"
It cleans all branches you’ve got locally that have already been merged.
— Safia (@captainsafia) November 3, 2018