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?
I use a git-flow esque naming scheme, so this works very safely for me:
git branch --merged | grep -e "^\s\+\(fix\|feature\)/" | xargs git branch -d
It basically looks for merged commits that start with either string fix/
or feature/
.
Based on some of these answers I made my own Bash script to do it too!
It uses git branch --merged
and git branch -d
to delete the branches that have been merged and prompts you for each of the branches before deleting.
merged_branches(){
local current_branch=$(git rev-parse --abbrev-ref HEAD)
for branch in $(git branch --merged | cut -c3-)
do
echo "Branch $branch is already merged into $current_branch."
echo "Would you like to delete it? [Y]es/[N]o "
read REPLY
if [[ $REPLY =~ ^[Yy] ]]; then
git branch -d $branch
fi
done
}
git branch --merged | %{git branch -d $_.Trim()}
If you want to exclude master or any other branch names, you can pipe with PowerShell Select-String like this and pass the result to git branch -d
:
git branch -d $(git branch --merged | Select-String -NotMatch "master" | %{$_.ToString().Trim()})
You can use git-del-br
tool.
git-del-br -a
You can install it via pip
using
pip install git-del-br
P.S: I am the author of the tool. Any suggestions/feedback are welcome.
Try the following command:
git branch -d $(git branch --merged | grep -vw $(git rev-parse --abbrev-ref HEAD))
By using git rev-parse
will get the current branch name in order to exclude it. If you got the error, that means there are no local branches to remove.
To do the same with remote branches (change origin
with your remote name), try:
git push origin -vd $(git branch -r --merged | grep -vw $(git rev-parse --abbrev-ref HEAD) | cut -d/ -f2)
In case you've multiple remotes, add grep origin |
before cut
to filter only the origin
.
If above command fails, try to delete the merged remote-tracking branches first:
git branch -rd $(git branch -r --merged | grep -vw $(git rev-parse --abbrev-ref HEAD))
Then git fetch
the remote again and use the previous git push -vd
command again.
If you're using it often, consider adding as aliases into your ~/.gitconfig
file.
In case you've removed some branches by mistake, use git reflog
to find the lost commits.
There is no command in Git that will do this for you automatically. But you can write a script that uses Git commands to give you what you need. This could be done in many ways depending on what branching model you are using.
If you need to know if a branch has been merged into master the following command will yield no output if myTopicBranch has been merged (i.e. you can delete it)
$ git rev-list master | grep $(git rev-parse myTopicBranch)
You could use the Git branch command and parse out all branches in Bash and do a for
loop over all branches. In this loop you check with above command if you can delete the branch or not.