如何删除已合并的分支?我可以一次删除所有分支,而不是逐个删除每个分支吗?


当前回答

git工具箱中的git清理脚本

删除所有已合并到主或发展让其他树枝到处乱放。删除时最保守。删除本地和源远程中的分支。

其他回答

为了避免意外地从master以外的任何其他分支运行命令,我使用以下bash脚本。否则,从已合并非主分支的分支运行git branch--merged |grep-v“\*”|xargs-n 1 git branch-d可能会删除主分支。

#!/bin/bash

branch_name="$(git symbolic-ref HEAD 2>/dev/null)" ||
branch_name="(unnamed branch)"     # detached HEAD
branch_name=${branch_name##refs/heads/}

if [[ $branch_name == 'master' ]]; then
   read -r -p "Are you sure? [y/N] " response
   if [[ $response =~ ^([yY][eE][sS]|[yY])$ ]]; then
       git branch --merged | grep -v "\*" | xargs -n 1 git branch -d
   fi
else
   echo "Refusing to delete branches that are not merged into '$branch_name'. Checkout master first."
fi

基于这些答案,我也制作了自己的Bash脚本来实现这一点!

它使用gitbranch--merged和gitbranch-d删除已合并的分支,并在删除之前提示您输入每个分支。

merged_branches () {
    local current_branch=$(git rev-parse --abbrev-ref HEAD)
    for branch in $(git branch --merged | cut -c3-)
      do
        echo "Branch $branch is already merged into $current_branch."
        echo "Would you like to delete it? [Y]es/[N]o "
        read REPLY
        if [[ $REPLY =~ ^[Yy] ]]; then
            git branch -d $branch
        fi
    done
}

编写一个脚本,Git将检查所有已合并到master的分支。

然后做git结账大师。

最后,删除合并的分支。

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

您可以将提交添加到--merged选项。这样,您可以确保只删除合并到原始/主文件中的分支

以下命令将从原点删除合并的分支。

git branch -r --merged origin/master | grep -v "^.*master" | sed s:origin/:: |xargs -n 1 git push origin --delete 

您可以测试将删除哪些分支来替换git推送原点--delete with echo

git branch -r --merged origin/master | grep -v "^.*master" | sed s:origin/:: |xargs -n 1 echo

使用Git版本2.5.0:

git branch -d `git branch --merged`