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

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

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

当前回答

差不多了。

只要忽略verify和quiet如果分支存在,你就得到哈希值如果分支不存在,你就什么都得不到。

将其赋值给一个变量并检查是否为空字符串。

exists=`git show-ref refs/heads/<branch-name>`
if [ -n "$exists" ]; then
    echo 'branch exists!'
fi

其他回答

git show-branch <BRANCH-NAME> &>/dev/null && echo yes || echo no

我认为你可以在这里使用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, 它将只在当地分支机构运作。

据我所知,这是在脚本中实现它的最佳方式。我不确定是否有更多的补充,但可能有一个答案只是说“这个命令做你想要的一切”:)

唯一需要注意的是分支名称中可能有令人惊讶的字符,因此可能需要引用<branch-name>。

在windows批处理脚本有点不同,

git rev-parse --verify <branch>

if %ERRORLEVEL% == 0  (
    echo "Yes"
) else (
    echo "No"
)
git branch --list $branch_name | grep $branch_name

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