如何删除已经合并的Git分支(附代码)

62 阅读1分钟

有很多旧的git分支挂在那里?这里有一个小脚本,可以删除已经加注的分支。

它将打印出要删除的分支,然后提示你是否要删除它们。

如果你的顶级分支不叫 "main",请自定义MAIN变量以匹配。

脚本 删除旧的git分支

#!/bin/bash

# Change this to match the name of your top level branch
MAIN=main

echo "These branches have been merged into $MAIN and will be deleted:"
echo
git branch --merged $MAIN | grep -v "^\* $MAIN"
echo

read -p "Continue? [y/N] " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]
then
  exit 1
fi

git branch --merged $MAIN | grep -v "^\* $MAIN" | xargs -n 1 -r git branch -d

把这段话复制/粘贴到你的 repo 或其他地方的一个文件中(比如git-cleanup.sh ),并使其可以用以下方式执行chmod +x git-cleanup.sh

奖励:如果你想让这个文件被忽略,但又不想用自己的本地脚本弄乱共享的.gitignore 文件,你可以编辑.git/info/exclude ,在那里列出这个文件。该文件可以作为本地的 gitignore。