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

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

    git branch --merged | grep -Ev '^(. master|\*)' | xargs -n 1 git branch -d will delete all local branches except the current checked out branch and/or master.

    Here's a helpful article for those looking to understand these commands: Git Clean: Delete Already Merged Branches, by Steven Harman.

    0 讨论(0)
  • 2020-11-22 15:01

    Below query works for me

    for branch in  `git branch -r --merged | grep -v '\*\|master\|develop'|awk 'NR > 0 {print$1}'|awk '{gsub(/origin\//, "")}1'`;do git push origin --delete $branch; done
    

    and this will filter any given branch in the grep pipe.

    Works well over http clone, but not so well for the ssh connection.

    0 讨论(0)
  • 2020-11-22 15:01

    Write a script in which Git checks out all the branches that have been merged to master.

    Then do git checkout master.

    Finally, delete the merged branches.

    for k in $(git branch -ra --merged | egrep -v "(^\*|master)"); do
      branchnew=$(echo $k | sed -e "s/origin\///" | sed -e "s/remotes\///")
      echo branch-name: $branchnew
      git checkout $branchnew
    done
    
    git checkout master
    
    for k in $(git branch -ra --merged | egrep -v "(^\*|master)"); do
      branchnew=$(echo $k | sed -e "s/origin\///" | sed -e "s/remotes\///")
      echo branch-name: $branchnew
      git push origin --delete $branchnew
    done
    
    0 讨论(0)
  • 2020-11-22 15:02

    kuboon's answer missed deleting branches which have the word master in the branch name. The following improves on his answer:

    git branch -r --merged | grep -v "origin/master$" | sed 's/\s*origin\///' | xargs -n 1 git push --delete origin
    

    Of course, it does not delete the "master" branch itself :)

    0 讨论(0)
  • 2020-11-22 15:03

    You can use gbda alias if you're using OhMyZSH with git plugin.

    0 讨论(0)
  • 2020-11-22 15:04

    On Windows with git bash installed egrep -v will not work

    git branch --merged | grep -E -v "(master|test|dev)" | xargs git branch -d
    

    where grep -E -v is equivalent of egrep -v

    Use -d to remove already merged branches or -D to remove unmerged branches

    0 讨论(0)
提交回复
热议问题