我正在使用下面的命令来查找在我的存储库中是否存在一个带有branch-name的本地git分支。这对吗?有没有更好的办法?

请注意,我是在脚本中执行此操作的。因此,如果可能的话,我希望使用管道命令。

git show-ref --verify --quiet refs/heads/<branch-name>
# $? == 0 means local branch with <branch-name> exists. 

当前回答

我对最初问题“更新”的“建议编辑”的审查结果是“它应该作为评论或答案写出来”,所以我把它贴在这里:

提出的另一种方法不仅将验证分支,还将验证任何具有@jhuynh这样名称的引用。

git rev-parse --verify <reference-name>
# $? == 0 means reference with <reference-name> exists.

关于初始问题的“更新”问题解释如下:

让我们假设并检查master。000'只是一个标记,这样的本地分支不存在,grep返回一个标记条目。如果引用存在,仍然rev-parse将返回0,即使这样的本地分支不存在。正如@paul-s所提到的,这是一个错误的匹配

$ git show-ref |grep master.000

f0686b8c16401be87e72f9466083d29295b86f4a refs/tags/master.000
$ git rev-parse --verify master.000
f0686b8c16401be87e72f9466083d29295b86f4a
$ echo $?
0

其他回答

我对最初问题“更新”的“建议编辑”的审查结果是“它应该作为评论或答案写出来”,所以我把它贴在这里:

提出的另一种方法不仅将验证分支,还将验证任何具有@jhuynh这样名称的引用。

git rev-parse --verify <reference-name>
# $? == 0 means reference with <reference-name> exists.

关于初始问题的“更新”问题解释如下:

让我们假设并检查master。000'只是一个标记,这样的本地分支不存在,grep返回一个标记条目。如果引用存在,仍然rev-parse将返回0,即使这样的本地分支不存在。正如@paul-s所提到的,这是一个错误的匹配

$ git show-ref |grep master.000

f0686b8c16401be87e72f9466083d29295b86f4a refs/tags/master.000
$ git rev-parse --verify master.000
f0686b8c16401be87e72f9466083d29295b86f4a
$ echo $?
0

当我在搜索引擎上搜索“git检查分支是否存在”时,这个页面是我看到的第一个页面。

我得到了我想要的,但我想提供一个更新的答案,因为最初的帖子是2011年的。

git rev-parse --verify <branch_name>

这本质上与接受的答案相同,但您不需要键入“refs/heads/<branch_name>”

从shell脚本来看,这将是

if [ `git rev-parse --verify main 2>/dev/null` ]
then
   ...
fi

我认为你可以在这里使用git show-branch。

$ git show-branch --list
  [master] test
* [testbranch] test
$ git show-branch testbranch
[testbranch] test
$ echo $?
0
$ git show-branch nonexistantbranch
fatal: bad sha1 reference nonexistantbranch
$ echo $?
128

所以,美元?== 0表示分支存在 你根本不需要去挖掘裁判/人头的管道。只要你不把-r传递给show-branch, 它将只在当地分支机构运作。

git branch --list $branch_name | grep $branch_name

然后检查返回值是0还是1。

这是我实现的方法,看起来更稳定

$branchExists = git ls-remote $gitUrl $gitBranch
if(!([bool]$branchExists))
{
   Write-Host "branch $branchName does not exist"  
} 
else
{
   Write-Host "branch $branchName exists"         
}

如果分支存在,则branchExist变量的内容将类似于:

hashcode of branch name         feature/my_branch