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

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

    I've been using the following method to remove merged local AND remote branches in one cmd.

    I have the following in my bashrc file:

    function rmb {
      current_branch=$(git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/')
      if [ "$current_branch" != "master" ]; then
        echo "WARNING: You are on branch $current_branch, NOT master."
      fi
      echo "Fetching merged branches..."
      git remote prune origin
      remote_branches=$(git branch -r --merged | grep -v '/master$' | grep -v "/$current_branch$")
      local_branches=$(git branch --merged | grep -v 'master$' | grep -v "$current_branch$")
      if [ -z "$remote_branches" ] && [ -z "$local_branches" ]; then
        echo "No existing branches have been merged into $current_branch."
      else
        echo "This will remove the following branches:"
        if [ -n "$remote_branches" ]; then
          echo "$remote_branches"
        fi
        if [ -n "$local_branches" ]; then
          echo "$local_branches"
        fi
        read -p "Continue? (y/n): " -n 1 choice
        echo
        if [ "$choice" == "y" ] || [ "$choice" == "Y" ]; then
          # Remove remote branches
          git push origin `git branch -r --merged | grep -v '/master$' | grep -v "/$current_branch$" | sed 's/origin\//:/g' | tr -d '\n'`
          # Remove local branches
          git branch -d `git branch --merged | grep -v 'master$' | grep -v "$current_branch$" | sed 's/origin\///g' | tr -d '\n'`
        else
          echo "No branches removed."
        fi
      fi
    }
    

    original source

    This doesn't delete the master branch, but removes merged local AND remote branches. Once you have this in you rc file, just run rmb, you're shown a list of merged branches that will be cleaned and asked for confirmation on the action. You can modify the code to not ask for confirmation as well, but it's probably good to keep it in.

提交回复
热议问题