使用通配符过滤git分支

时间:2018-03-12 14:48:57

标签: git github

我正在尝试列出包含'功能'的所有分支机构。在里面。 在此发布之前,我已经提到了提供的解决方案here

那里提供的解决方案对我不起作用 - 即; git branch --list "*feature*"git branch --list \*feature\*

当我从终端尝试时,它不会按预期返回分支列表。有人可以告诉我可能的原因和可能的解决方案,如果有的话。

最终目标是删除作为列表

的一部分返回的所有分支

2 个答案:

答案 0 :(得分:3)

我在本地有以下分支:

git branch --list
  1test
  2test
  3test
* master
  t1
  t2
  t3
  test1
  test2
  test3
  test4

此命令将搜索名为test*本地分支并删除它们:

git branch --list 'test*' --format '%(refname:short)' | xargs git branch -d
Deleted branch test1 (was fca79ef34c04).
Deleted branch test2 (was fca79ef34c04).
Deleted branch test3 (was fca79ef34c04).
Deleted branch test4 (was fca79ef34c04).

默认情况下,--list只会显示本地分支。您可以在git documentation中看到您可以提供-r仅显示远程分支,或-a以显示远程和本地分支。让我们更新上一个命令以便为远程分支工作。

git branch --list 'test*' -r --format '%(refname:short)' | xargs git push -d origin

您也可以尝试使用带有完整参考的命令:

git branch --list 'test*' -r --format '%(refname)' | xargs git push -d origin

答案 1 :(得分:2)

列出所有包含“功能”的分支(本地和远程):
git branch --all --list "*feature*"

仅列出包含“功能”的远程分支:
git branch --remotes --list "origin/*feature*"

作为Jim saidgit branch --format '%(refname)'输出每个分支的完整refname。

因此,如果OP想要尝试从服务器中删除所有以'feature /'开头的远程分支,请放在一起:
git branch -rl "origin/feature/*" --format "%(refname)" | xargs git push --dry-run -d origin

⚠️仅在确认分支列表后才删除--dry-run


注意:

  • 没有--all,OP的初始解决方案无法工作,因为分支是远程的。
  • 使用-r, --remotes的建议不起作用,因为远程分支名称采用<remote>/<branch>git book)的形式;因此,模式需要以遥控器的名称开头,例如origin/(尽管毗湿奴的suggestion通过以*开始模式确实起作用了)
  • -a-r的输出略有不同。
# Example: feature/{foo,new} are local, and feature/{foo,bar,baz} are all remote

$ git branch -al "*feature*"
  feature/foo
  feature/new
  remotes/origin/feature/bar
  remotes/origin/feature/baz
  remotes/origin/feature/foo
# ^^ remote branches are qualifed with 'remotes/' prefix

$ git branch -rl "origin/*feature*"
  origin/feature/bar
  origin/feature/baz
  origin/feature/foo
# ^^ branches are known to be remote, so prefix 'remotes/' is dropped

$ git branch -rl "origin/feature/*" --format "%(refname)"
refs/remotes/origin/feature/bar
refs/remotes/origin/feature/baz
refs/remotes/origin/feature/foo
# ^^ full refnames start with 'refs/'

$ git branch -rl "origin/feature/*" --format "%(refname)" | xargs git push --dry-run -d origin
To github.com:foo1-org/foo1.git
 - [deleted]         origin/feature/bar
 - [deleted]         origin/feature/baz
 - [deleted]         origin/feature/foo