Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete all Git remote branches except master?

Tags:

git

github

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.

like image 336
willsteel Avatar asked Feb 21 '19 13:02

willsteel


People also ask

How do I delete all remote branches except master?

We use the grep -v "master" command to search for branches except the master then we delete them using the git branch -D command.

How do I delete a remote branch only?

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 .

How do I delete multiple branches in git?

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.

How do I delete all local branches?

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 .


1 Answers

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;
like image 138
staxim Avatar answered Oct 11 '22 13:10

staxim