Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
delete all remote branches that have already been merged into master
$ git branch -r --merged |
awk -F'/' '/^ *origin/{if(!match($0, /(>|master)/)){print $2}}' |
xargs git push origin --delete
@Spitfire1900
Copy link

Spitfire1900 commented Jun 17, 2014

Should be useful for future projects.

Loading

@MarcoSero
Copy link

MarcoSero commented Sep 11, 2014

It doesn't work for branches named like feature/123

Loading

@hernanflores
Copy link

hernanflores commented Jan 4, 2016

The first command should be git branch -r --merged origin/master . As it is, this script deletes any branch merged with some branch in origin.

Loading

@brbsix
Copy link

brbsix commented Apr 30, 2016

This should fix the issue with feature branches:

git branch -r --merged origin/master \
    | awk -F/ '/^\s*origin/ {if (!match($0, /origin\/master/)) {sub("^\\s*origin/", ""); print}}' \
    | xargs -rpn1 git push origin --delete

The xargs flags are as follows:

-n1 delete branches one at a time
-p prompt the user for confirmation immediately prior to deleting a branch
-r ensure git push origin --delete with not be run if there are no branches to delete

Loading

@talsafran
Copy link

talsafran commented Feb 11, 2017

Thanks for sharing this! I'm getting the following error though:

xargs: illegal option -- r
usage: xargs [-0opt] [-E eofstr] [-I replstr [-R replacements]] [-J replstr]
             [-L number] [-n number [-x]] [-P maxprocs] [-s size]
             [utility [argument ...]]

Anyone else getting this? Running on MacOS Sierra.

Loading

@TrevorSayre
Copy link

TrevorSayre commented Feb 17, 2017

@talsafran Yep, -r is not an option on MacOS xargs (see: man xargs)
-r is a GNU extension

You can install GNU xargs through Homebrew and the GNU findutils package.
brew install findutils

This will give you GNU xargs as gxargs, and you can use the -r option

The same goes for other basic commands found in the findutils package such as gfind or glocate or gupdatedb, which have different BSD counterparts on OS X.

After installing findutils, the command on MacOS will be:

git branch -r --merged origin/master \
    | awk -F/ '/^\s*origin/ {if (!match($0, /origin\/master/)) {sub("^\\s*origin/", ""); print}}' \
    | gxargs -rpn1 git push origin --delete

Loading

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment