Delete all local git branches
The 'git branch -d' subcommand can delete more than one branch. So, simplifying @sblom's answer but adding a critical xargs:
git branch -D `git branch --merged | grep -v \* | xargs`
or, further simplified to:
git branch --merged | grep -v \* | xargs git branch -D
Importantly, as noted by @AndrewC, using git branch
for scripting is discouraged. To avoid it use something like:
git for-each-ref --format '%(refname:short)' refs/heads | grep -v "master\|main" | xargs git branch -D
Caution warranted on deletes!
$ mkdir br
$ cd br; git init
Initialized empty Git repository in /Users/ebg/test/br/.git/
$ touch README; git add README; git commit -m 'First commit'
[master (root-commit) 1d738b5] First commit
0 files changed, 0 insertions(+), 0 deletions(-)
create mode 100644 README
$ git branch Story-123-a
$ git branch Story-123-b
$ git branch Story-123-c
$ git branch --merged
Story-123-a
Story-123-b
Story-123-c
* master
$ git branch --merged | grep -v \* | xargs
Story-123-a Story-123-b Story-123-c
$ git branch --merged | grep -v \* | xargs git branch -D
Deleted branch Story-123-a (was 1d738b5).
Deleted branch Story-123-b (was 1d738b5).
Deleted branch Story-123-c (was 1d738b5).
The simpler way to delete all branches but keeping others like "develop" and "master" is the following:
git branch | grep -v "develop" | grep -v "master" | xargs git branch -D
very useful !