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

后端 未结 30 1448
离开以前
离开以前 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:07

    Note: I am not happy with previous answers, (not working on all systems, not working on remote, not specifying the --merged branch, not filtering exactly). So, I add my own answer.

    There are two main cases:

    Local

    You want to delete local branches that are already merged to another local branch. During the deletion, you want to keep some important branches, like master, develop, etc.

    git branch --format "%(refname:short)" --merged master | grep -E -v '^master$|^feature/develop$' | xargs -n 1 git branch -d
    

    Notes:

    • git branch output --format ".." is to strip whitespaces and allow exact grep matching
    • grep -E is used instead of egrep, so it works also in systems without egrep (i.e.: git for windows).
    • grep -E -v '^master$|^feature/develop$' is to specify local branches that I don't want to delete
    • xargs -n 1 git branch -d: perform the deletion of local branches (it won't work for remote ones)
    • of course you get an error if you try deleting the branch currently checked-out. So, I suggest to switch to master beforehand.

    Remote

    You want to delete remote branches that are already merged to another remote branch. During the deletion, you want to keep some important branches, like HEAD, master, releases, etc.

    git branch -r --format "%(refname:short)" --merged origin/master | grep -E -v '^*HEAD$|^*/master$|^*release' | cut -d/ -f2- | xargs -n 1 git push --delete origin
    

    Notes:

    • for remote, we use the -r option and provide the full branch name: origin/master
    • grep -E -v '^*HEAD$|^*/master$|^*release' is to match the remote branches that we don't want to delete.
    • cut -d/ -f2- : remove the unneeded 'origin/' prefix that otherwise is printed out by the git branch command.
    • xargs -n 1 git push --delete origin : perform the deletion of remote branches.

提交回复
热议问题