Deleting a single local Git branch in our machine is quite simple:
git branch -D <branch_name>
But if we have more than 10 branches (which is very possible) repeating that command is a bad choice and takes time. Then I search the internet about the git command on how to delete all branches except the master.
Why the master branch? Because the default root branch in Git is master and many programmers use the code inside it as the base code before deploying the application. And here’s what I found:
git branch | grep -ve " master$" | xargs git branch -D
That command is consists of multiple commands that produce multiple results, there are:
- List all branch’s name that has a prefix of
- Take all that branch’s name and pass it as the argument into
git branch -Dcommand.
I tried the command and it works flawlessly, but it got 1 problem. It is the name of the branch. I think we as a programmer will sometime need to delete all existing branches including the master, but excluding the other name.
So I decided to create a simple bash script to run a git command, which can delete all branches except 1 branch.
The script is simple, it’s only taking a single argument that will replace the branch name inside the git command.
Here is the script:
To run the script you just need to type:
If you want to view the complete script, that has a
help page, you can see it from my repo:
Simple Git Branch Removal. Contribute to ridhoperdana/brove development by creating an account on GitHub.
Have a nice day! 🖖