Delete all git branches except master

git branch | grep -v "master" | sed 's/^[ *]*//' | sed 's/^/git branch -D /' | bash
Delete all your branches except master (useful after archiving branches)
Sample Output
Deleted branch testbranch (was d15d722).

By: Trindaz
2015-01-31 00:29:32

What Others Think

Hmm... In the middle sed you filter out * (meaning the current branch). If you don't checkout master first, deleting the current branch will fail. That said, you can simplify the command using sed only: git checkout master; git branch | sed -e '/master/d' -e 's/^/git branch -D /' | bash
flatcap · 351 weeks ago
If you keep your command as is I'd replace the grep for 'master' with an egrep matching the full word 'master.' Otherwise, all of the following valid branch names that contain 'master' will also be excluded along with 'master': mastermind masterpiece master-of-puppets whos-the-master-SHO-NUFF etc. git branch | egrep -v ^master$ | sed 's/^[ *]*//' | sed 's/^/git branch -D /' | bash Having said that, flatcap has a better suggestion.
dmengelt · 350 weeks and 3 days ago

What do you think?

Any thoughts on this command? Does it work on your machine? Can you do the same thing with only 14 characters?

You must be signed in to comment.

What's this? is the place to record those command-line gems that you return to again and again. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.

Share Your Commands

Stay in the loop…

Follow the Tweets.

Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.


Subscribe to the feeds.

Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):

Subscribe to the feed for: