我想清理我的本地存储库,它有大量的旧分支:例如3.2、3.2.1、3.2.2等。

我希望有个鬼鬼祟祟的办法能一次性把他们干掉。因为它们大多遵循点释放约定,我想也许有一个捷径可以说:

git branch -D 3.2.*

并杀死所有3.2。x分支。

我尝试了这个命令,当然,它不起作用。


当前回答

git branch  | cut -c3- | egrep "^3.2" | xargs git branch -D
  ^                ^                ^         ^ 
  |                |                |         |--- create arguments
  |                |                |              from standard input
  |                |                |
  |                |                |---your regexp 
  |                |
  |                |--- skip asterisk 
  |--- list all 
       local
       branches

编辑:

一个更安全的版本(由Jakub narabbski和Jefromi建议),因为git分支输出并不用于脚本:

git for-each-ref --format="%(refname:short)" refs/heads/3.2\* | xargs git branch -D

... 或者xargs-free:

git branch -D `git for-each-ref --format="%(refname:short)" refs/heads/3.2\*`

其他回答

要根据指定的模式删除多个分支,请执行以下操作:

打开终端或同等工具,输入以下命令:

git branch | grep "<pattern>" (preview of the branches based on pattern)

git branch | grep "<pattern>" | xargs git branch -D (replace the <pattern> with a regular expression to match your branch names)

删除所有3.2。X个分支,你需要输入

git branch | grep "3.2" | xargs git branch -D

这是所有!

你可以开始了!

如果你正在使用Fish shell,你可以利用字符串函数:

git branch -d (git branch -l "<your pattern>" | string trim)

这与其他一些答案中的Powershell选项没有太大区别。

对于使用PowerShell的纯灵魂,这里有一个小脚本 Git branch -d $(Git branch——list '3.2.;*' | %{$_.Trim()})

也许你会发现这很有用:

如果你想删除所有不是'master', 'foo'和'bar'的分支

git branch -D `git branch | grep -vE 'master|foo|bar'`

Grep -v 'something'是一个带有反转的匹配器。

你可能会喜欢这个小物件…在最终删除所有选择之前,它会拉出列表并要求确认每个项目……

git branch -d `git for-each-ref --format="%(refname:short)" refs/heads/\* | while read -r line; do read -p "remove branch: $line (y/N)?" answer </dev/tty; case "$answer" in y|Y) echo "$line";; esac; done`

使用-D强制删除(像往常一样)。

为了可读性,这里是逐行分解的…

git branch -d `git for-each-ref --format="%(refname:short)" refs/heads/\* |
    while read -r line; do 
        read -p "remove branch: $line (y/N)?" answer </dev/tty;
        case "$answer" in y|Y) echo "$line";; 
        esac; 
    done`

下面是xargs方法……

git for-each-ref --format="%(refname:short)" refs/heads/\* |
while read -r line; do 
    read -p "remove branch: $line (y/N)?" answer </dev/tty;
    case "$answer" in 
        y|Y) echo "$line";; 
    esac; 
done | xargs git branch -D

最后,我喜欢把它放在。bashrc中

alias gitselect='git for-each-ref --format="%(refname:short)" refs/heads/\* | while read -r line; do read -p "select branch: $line (y/N)?" answer </dev/tty; case "$answer" in y|Y) echo "$line";; esac; done'

这样我就可以说

gitSelect | xargs git branch -D.