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

Solution 1:

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

will delete all branches except master (replace master with branch you want to keep, but then it will delete master)

Solution 2:

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.

Solution 3:

first (switch to the branch you want to keep > ex: master):

git checkout master

second (make sure you are on master)

git branch -D $(git branch)