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

后端 未结 14 2467
广开言路
广开言路 2020-12-12 13:07

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

$ git branch

... but keeping current branch, in one step. Is th

14条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-12 13:30

    git branch -d (or -D) allows multiple branch names, but it's a bit tricky to automatically supply "all local branches excluding the one I'm on now" without writing at least a little bit of code.

    The "best" (formally correct) method is to use git for-each-ref to get the branch names:

    git for-each-ref --format '%(refname:short)' refs/heads
    

    but then it's even harder to figure out which branch you're on (git symbolic-ref HEAD is the "formally correct" method for this, if you want to write a fancy script).

    More conveniently, you can use git branch, which prints your local branch names preceded by two spaces or (for the current branch) by an asterisk *. So, run this through something to remove the * version and you're left with space-separated branch names, which you can then pass to git branch -d:

    git branch -d $(git branch | grep -v '^*')
    

    or:

    git branch | grep -v '^*' | xargs git branch -d
    

    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.

提交回复
热议问题