How can I delete all Git branches which have been merged?

后端 未结 30 1449
离开以前
离开以前 2020-11-22 14:22

I have many Git branches. How do I delete branches which have already been merged? Is there an easy way to delete them all instead of deleting them one by one?

30条回答
  •  青春惊慌失措
    2020-11-22 15:17

    Try the following command:

    git branch -d $(git branch --merged | grep -vw $(git rev-parse --abbrev-ref HEAD))
    

    By using git rev-parse will get the current branch name in order to exclude it. If you got the error, that means there are no local branches to remove.

    To do the same with remote branches (change origin with your remote name), try:

    git push origin -vd $(git branch -r --merged | grep -vw $(git rev-parse --abbrev-ref HEAD) | cut -d/ -f2)
    

    In case you've multiple remotes, add grep origin | before cut to filter only the origin.

    If above command fails, try to delete the merged remote-tracking branches first:

    git branch -rd $(git branch -r --merged | grep -vw $(git rev-parse --abbrev-ref HEAD))
    

    Then git fetch the remote again and use the previous git push -vdcommand again.

    If you're using it often, consider adding as aliases into your ~/.gitconfig file.

    In case you've removed some branches by mistake, use git reflog to find the lost commits.

提交回复
热议问题