Looking for a command to delete all branches on Git repository except for master and push them to remote.
This is to clean up Git repository before making a release as the previous history branches everything else are totally dev changes and doesn't matter.
We use the grep -v "master" command to search for branches except the master then we delete them using the git branch -D command.
To delete a remote branch, you can't use the git branch command. Instead, use the git push command with --delete flag, followed by the name of the branch you want to delete. You also need to specify the remote name ( origin in this case) after git push .
You can use git gui to delete multiple branches at once. From Command Prompt/Bash -> git gui -> Remote -> Delete branch ... -> select remote branches you want to remove -> Delete.
From the UI go to Branch --> Delete and Ctrl+Click the branches you want to delete so they are highlighted. If you want to be sure they are merged into a branch (such as dev ), under Delete Only if Merged Into set Local Branch to dev .
This will remove all branches (except for master
), even if the branch has a slash '/' in it:
git branch -r | grep 'origin' | grep -v 'master$' | grep -v HEAD | cut -d/ -f2- | while read line; do git push origin :heads/$line; done;
This will do the same, leaving both develop
and master
branches alone:
git branch -r | grep 'origin' | grep -v 'master$' | grep -v 'develop$' | grep -v HEAD | cut -d/ -f2- | while read line; do git push origin :heads/$line; done;
This is the script for fish shell:
git branch -r | grep 'origin' | grep -v 'master$' | grep -v 'develop$' | grep -v HEAD | cut -d/ -f2- | while read line; git push origin :heads/$line; end;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With