Git 批量清理本地分支
批量清理除特定几个分支外的所有其他本地分支。
前言
Q: 我的自动化叒整出了一大堆没用的本地分支,怎么办呀!
Q: 我该如何在自动化的最后清理掉这些分支呢?
A: 别慌!一条命令就可以实现!
方法
手动删除
PowerShell
powershell
git branch | Where-Object { $_ -notlike "master" } | ForEach-Object { git branch -D $_.Trim() } # 过滤单个
git branch | Where-Object { $_ -notlike "master" -and $_ -notlike "develop" } | ForEach-Object { git branch -D $_.Trim() } # 过滤多个,还要的话继续加 -and $_ -notlike "分支名"
git branch | Where-Object { $_ -notmatch "^(master|develop|release\/.*)$" } | ForEach-Object { git branch -D $_.Trim() } # 过滤多个,使用正则匹配 master develop release 这三个分支git branch列出所有本地分支。Where-Object { $_ -notlike "master" }过滤掉指定的分支。ForEach-Object { git branch -D $_.Trim() }逐个删除剩下的分支。$_表示当前项,Trim()用来去掉分支名两侧的空格。
提示
如果你当前签出在某个需要过滤掉的分支上时,git branch会将那个分支输出为* 分支名,所以在排除时也需要使用相同格式。(你就算忘了也没关系,git会提示error: branch '* 分支名' not found)
bash
bash
git branch | grep -v "master" | xargs git branch -D # 过滤单个,这里假设 master* 解释同上方的 PowerShell 代码解释
自动化中
虽然语言不同、代码不同,但逻辑一样。
具体解释前面说过了,这里就不再讲了。
Python
python
import subprocess
# 获取所有本地分支
branches = subprocess.check_output(["git", "branch"]).decode("utf-8").splitlines()
# 过滤分支
exclude_branches = ["master", "develop"] # 过滤掉啥这里设啥,可以只设1个
branches_to_delete = [branch.strip() for branch in branches if not any(exclude in branch for exclude in exclude_branches)]
# 删除分支
for branch in branches_to_delete:
subprocess.run(["git", "branch", "-D", branch])JavaScript (Node.js)
javascript
const { execSync } = require('child_process'); // ES
// 获取所有本地分支
const branches = execSync('git branch').toString().split('\n');
// 过滤分支
const excludeBranches = ['master', 'develop']; // 过滤掉啥这里设啥,可以只设1个
const branchesToDelete = branches.filter(branch =>
!excludeBranches.some(exclude => branch.includes(exclude))
).map(branch => branch.trim());
// 删除分支
branchesToDelete.forEach(branch => {
execSync(`git branch -D ${branch}`);
});C#
csharp
// .NET 8 控制台应用
using System.Diagnostics;
class Program
{
internal static readonly char[] separator = ['\n'];
static void Main()
{
// 获取所有本地分支
var branches = RunGitCommand("git branch");
// 过滤分支
var excludeBranches = new[] { "master", "develop" };
var branchesToDelete = branches.Split(separator, StringSplitOptions.RemoveEmptyEntries);
foreach (var branch in branchesToDelete)
{
if (Array.TrueForAll(excludeBranches, exclude => !branch.Contains(exclude)))
{
RunGitCommand($"git branch -D {branch.Trim()}");
}
}
}
static string RunGitCommand(string command)
{
var processStartInfo = new ProcessStartInfo("cmd", $"/c {command}") // CMD
{
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
var process = Process.Start(processStartInfo);
return process.StandardOutput.ReadToEnd(); // 警告 CS8602 解引用可能出现空引用。 - 如果确保有删除分支可以忽略
}
}C++
cpp
#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
#include <fstream>
int main() {
// 获取所有本地分支并存到 branches.txt 中
system("git branch > branches.txt");
// 过滤分支
std::vector<std::string> excludeBranches = {"master", "develop"};
// 读取文件中的分支名称
std::ifstream file("branches.txt"); // 从 branches.txt 中读取所有本地分支
std::string line;
while (std::getline(file, line)) {
bool exclude = false;
for (const auto& excludeBranch : excludeBranches) {
if (line.find(excludeBranch) != std::string::npos) {
exclude = true;
break;
}
}
if (!exclude) {
std::string branch = line;
branch.erase(branch.find_last_not_of(" \n\r\t") + 1);
system(("git branch -D " + branch).c_str()); // 删分支
}
}
return 0;
}