gitbashubuntuversion-controlgrep

Delete all local Git branches


I follow a development process where I create a new local branch for every new feature or story card. When finished I merge the branch into master and then push.

What tends to happen over time due to a combination of laziness or forgetfulness, is that I end up with a large list of local branches, some of which (such as spikes) may not have been merged.

I know how to list all my local branches and I know how to remove a single branch but I was wondering if there was a Git command that allows me to delete all my local branches?

Below is the output of the git branch --merged command.

cd ~/projects/application
git branch --merged

Output:

  STORY-123-Short-Description
  STORY-456-Another-Description
  STORY-789-Blah-Blah
* master

All attempts to delete branches listed with grep -v \* (as per the answers below) result in errors:

error: branch 'STORY-123-Short-Description' not found.
error: branch 'STORY-456-Another-Description' not found.
error: branch 'STORY-789-Blah-Blah' not found.

I'm using:


Solution

  • 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).