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

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

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

当前回答

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

$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

其他回答

当我在搜索引擎上搜索“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 is_localbranch(您需要在.gitconfig中添加别名)。

用法:

$ git is_localbranch BRANCH

来源:

git branch | grep -w $1 > /dev/null
if [ $? = 0 ]
then
  echo "branch exists"
fi
git branch --list $branch_name | grep $branch_name

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

git show-ref和git rev-parse都不能在我的情况下工作。

$ git --version
git version 2.21.0

$ git show-branch --list
* [master] mybranch commit

$ BRANCH_NAME=mybranch
$ git rev-parse --verify $BRANCH_NAME
fatal: Needed a single revision

$ git show-ref refs/heads/$BRANCH_NAME
<no otput>
$ [ $? == 0 ] && echo "$BRANCH_NAME exists" || echo "$BRANCH_NAME not exists"
mybranch not exists

最后得到了这个

$ BRANCH_NAME=mybranch
$ SHOW_ALL=`git show-branch --all | grep -w $BRANCH_NAME`
$ [ $? == 0 ] && echo "$BRANCH_NAME exists" || echo "$BRANCH_NAME not exists"
mybranch exists

您也可以使用脚本文件

#!/bin/sh
BRANCH_NAME=mybranch
if grep -Fqe $BRANCH_NAME << EOF
`git show-branch --all`
EOF
then
   echo "$BRANCH_NAME exists"
else
   echo "$BRANCH_NAME not exists"
fi

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

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