Today's trick is small and beautiful.

In git, you constantly create and merge branches (if not, you're doing it wrong 😉).

In my case, it's often like this:

  • Create a new branch locally
  • Start working on the branch, adding commits as I go
  • Eventually (usually after the first commit), push the branch to the origin on GitHub / GitLab / …
  • Create a merge / pull request for review
  • After review, the branch gets merged and the origin branch on GitHub / GitLab / … is removed

Once you're at that point, you should remember to remove the local branch to avoid confusion. It's this last step which becomes tedious if you have many branches at the same time.

Luckily, with some clever terminal ninja commands, you can automate the removal of the local branches which have been merged:

$ git branch --merged | grep -Ev "(^\*|^\s+(master|main|develop)$)" | xargs git branch -d

Read it as follows:

  • Step 1 is to get all branches which have been merged (git branch --merged)
  • Step 2 is to remove main, master and/or develop from that list (grep -Ev "(^\*|master|main|develop)")
  • Step 3 is to remove each of these branches xargs git branch -d

If you want, you can easily turns this in a command by declaring the following alias in your ~/.zprofile (or equivalent):

alias cl='git pull -q && git branch --merged | grep -Ev "(^\*|^\s+(master|main|develop)$)" | xargs git branch -d'

PS: you should do a git pull before running this command so that your working copy is up-to-date.