-
-
Save schacon/942899 to your computer and use it in GitHub Desktop.
$ git branch -r --merged | | |
grep origin | | |
grep -v '>' | | |
grep -v master | | |
xargs -L1 | | |
awk '{split($0,a,"/"); print a[2]}' | | |
xargs git push origin --delete |
I created a script named git-merged
on my PATH. Git recognizes this syntax and allows you to execute these scripts as if they are aliases. In this case, this script allows you to run git merged
. The contents of the script are as follows:
#!/usr/bin/env bash
remote="${1:-origin}"
branch="$2"
git branch -r --list "$remote/*" --merged $branch \
| sed "s/\s*$remote\///" \
| egrep -v "^(HEAD|release|hotfix|master|develop)"
With this script, you can list merged branches on the remote (default behavior is to check remote origin
for branches merged to HEAD
):
$ git merged
You can fully specify the remote and target branch to check for merges:
$ git merged origin my-topic
Example above checks all remote tracking branches on remote origin
that are merged to local branch my-topic
. Using xargs
, you can use this to effectively delete all merged branches on the remote:
$ git merged | xargs git push origin --delete
You can add the -n
option to do a dry push to verify what will happen before you actually delete anything:
$ git merged | xargs git push origin --delete -n
The following branch patterns are ignored (supports git-flow branch naming):
release/1.2.3
hotfix/1.2.3
develop
master
origin/HEAD
The intention is to explicitly clean up stale, merged branches for feature development such as:
feature/my-thing
bugfix/crash-issue
my-topic-branch
Could you replace the current awk statement that resides in the gist file with the suggestion by @catsby, i.e. awk '{sub(/origin\//,"");print}'
?
Here's a bash version, that doesn't rely on awk
or sed
or xargs
.
for branch in $(git branch -r --merged master | grep origin | grep -v develop | grep -v master);
do
git push origin --delete "${branch##*/}";
done
Here's a bash version, that doesn't rely on
awk
orsed
orxargs
.for branch in $(git branch -r --merged master | grep origin | grep -v develop | grep -v master); do git push origin --delete "${branch##*/}"; done
Clearest solution I've seen, it makes the intent much more explicit than a long chain of awk/sed/xarg calls.
Only thing I'd add is that it doesn't quite work for branches that have a '/' in the name - if branch="origin/foo/bar" then ${branch##*/} will be "bar" and not "foo/bar"! You can fix by using the non-greedy single # to match the substring:
for branch in $(git branch -r --merged master | grep origin | grep -v develop | grep -v master)
do
git push origin --delete "${branch#*/}"
done
My solution to prune merged branches from local + multiple remotes, based on snippets above:
https://gist.github.com/ryanc414/f7686d2c97808b41ed8518a5840e2d78
Best answer in my opinion @voiski 👏 👏 👏