Remove merged local git branches

Command and how it works explanation

Posted on 2017-03-15 08:51:32

Quite often you may face this trivial problem - remove merged local git branches. Usually we just go to google, type this query and follow the best StackOverflow answer.

The solution is:

git branch --merged | egrep -v "(^\*|master|dev)" | xargs git branch -d

But how it works? Actually there are 3 commands merged in a single pipeline:

  1. git brach --merged - just returns a list of merged branches, including master and current branch.
  2. egrep -v(^\*|master|dev) - filters branches to remove master, dev and current branch name(current branch name starts with * char)
  3. xargs git branch -d - simply takes the output of egrep and uses it as arguments for git branch -d command.

Of course the topic is much more complicated, and we can discuss regex, xargs and git infinitely, but briefly that’s how it works.