Can I delete all the local branches except the current one?

Issue

I want to delete all branches that get listed in the output of …

$ git branch

… but keeping current branch, in one step. Is that possible? If so, how?

Solution

Based on @pankijs answer, I made two git aliases:

[alias]
    # Delete all local branches but master and the current one, only if they are fully merged with master.
    br-delete-useless = "!f(){\
        git branch | grep -v "master" | grep -v ^* | xargs git branch -d;\
    }; f"
    # Delete all local branches but master and the current one.
    br-delete-useless-force = "!f(){\
        git branch | grep -v "master" | grep -v ^* | xargs git branch -D;\
    }; f"

To be added in ~/.gitconfig


And, as @torek pointed out:

Note that lowercase -d won’t delete a “non fully merged” branch (see the documentation). Using -D will delete such branches, even if this causes commits to become “lost”; use this with great care, as this deletes the branch reflogs as well, so that the usual “recover from accidental deletion” stuff does not work either.

Basically, never use the -force version if you’re not 300% sure you won’t lose anything important. Because it’s lost forever.

Answered By – Vadorequest

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published