DEV Community

miku86
miku86

Posted on

Git: Delete merged branches

Problem

I build an app and use git branches.

Branches sum up, I don't know which branches are already merged into master and I lose overview.

git branch

many git branches

Solution (Linux)

I need a command that checks if a branch is merged into master and if it is merged, it should get deleted locally.

  1. git checkout master (or whatever branch you want to compare to)

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

less git branches

Explanation

  1. git branch --merged: List all branches whose tips are reachable from the specified commit (HEAD if not specified).
  2. egrep -v "(^\*|master|dev)": Search for all lines that do not start with * (= the current branch), or don't have master or dev in it.
  3. xargs git branch -d: Execute the command to delete all found branches from step 2.

Further Reading

Top comments (5)

Collapse
 
marounmaroun profile image
Maroun Maroun

Add it as an alias in your ~/.gitconfig:

[alias]
    delete-merged = git branch --merged | egrep -v "(^\*|master|dev)" | xargs git branch -d
Collapse
 
miku86 profile image
miku86

Great idea!

Collapse
 
thinkdigitalsoftware profile image
ThinkDigitalSoftware

Hey, is this a post with a solution? Do you have a complete script?

Collapse
 
miku86 profile image
miku86

Hey,

there is the Solution (Linux)-section with the two-step solution.
For Windows, there is a link in the Further Reading-section

Some comments may only be visible to logged-in visitors. Sign in to view all comments.