Question:
I want to delete all branches that get listed in the output of …
1 2 |
$ git branch |
… but keeping current branch, in one step. Is that possible? If so, how?
Answer:
Based on @pankijs answer, I made two git aliases:
1 2 3 4 5 6 7 8 9 10 |
[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.