I have many Git branches. How do I delete branches which have already been merged? Is there an easy way to delete them all instead of deleting them one by one?
git branch --merged | grep -Ev '^(. master|\*)' | xargs -n 1 git branch -d
will delete all local branches except the current checked out branch and/or master
.
Here's a helpful article for those looking to understand these commands: Git Clean: Delete Already Merged Branches, by Steven Harman.
Below query works for me
for branch in `git branch -r --merged | grep -v '\*\|master\|develop'|awk 'NR > 0 {print$1}'|awk '{gsub(/origin\//, "")}1'`;do git push origin --delete $branch; done
and this will filter any given branch in the grep pipe.
Works well over http clone, but not so well for the ssh connection.
Write a script in which Git checks out all the branches that have been merged to master.
Then do git checkout master
.
Finally, delete the merged branches.
for k in $(git branch -ra --merged | egrep -v "(^\*|master)"); do
branchnew=$(echo $k | sed -e "s/origin\///" | sed -e "s/remotes\///")
echo branch-name: $branchnew
git checkout $branchnew
done
git checkout master
for k in $(git branch -ra --merged | egrep -v "(^\*|master)"); do
branchnew=$(echo $k | sed -e "s/origin\///" | sed -e "s/remotes\///")
echo branch-name: $branchnew
git push origin --delete $branchnew
done
kuboon's answer missed deleting branches which have the word master in the branch name. The following improves on his answer:
git branch -r --merged | grep -v "origin/master$" | sed 's/\s*origin\///' | xargs -n 1 git push --delete origin
Of course, it does not delete the "master" branch itself :)
You can use gbda
alias if you're using OhMyZSH with git plugin.
git branch --merged | grep -E -v "(master|test|dev)" | xargs git branch -d
where grep -E -v
is equivalent of egrep -v
Use -d
to remove already merged branches or
-D
to remove unmerged branches