← Back
git

Remove git branches

I want to remove my unused branches in the repo. For example, all fixes:

git branch | grep "fix/*" | xargs git branch -D

It works with any grep pattern. Grep has this "-v" option to filter instead of find. So this way you can remove all branches except master:

git branch | grep -v master | xargs git branch -D

Use with caution :-)

Update: recover removed branches #

You can recover a deleted branch by using the SHA1 of the commit:

git checkout -b <branch> <sha>

For example, if you delete a branch accidentally (like the first one in this example):

❯ git branch | grep "fix/*" | xargs git branch -D
Deleted branch APP-100/fix-lint-issues (was b75a38dd).
Deleted branch fix/APP-101/change-window-text-description (was a041dcd6).
Deleted branch fix/APP-102/fix-end-of-month-bug (was f5a5ed89).
Deleted branch fix/APP-451/remove-month-label (was 38a09351)

You can recover it with:

git co -b  APP-100/fix-lint-issues b75a38dd

Related: git reference logs Source: https://stackoverflow.com/a/3640806