我正在使用下面的命令来查找在我的存储库中是否存在一个带有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

其他回答

如果您能设法包括grep。

git branch | grep -q <branch>

对于在脚本中使用,我建议使用以下命令:

git ls-remote --heads <repo_url> "<branch_name>" | wc -l

注意,<repo_url>可以只是一个“。”来指定本地回收(如果您在其目录结构中)、本地回收的路径或远程回收的地址。

如果<branch_name>不存在,则该命令返回0,如果存在则返回1。

Git branch -l <branch-name>

如果分支存在,则返回分支名称;如果分支不存在,则返回none

我推荐git show-ref——quiet refs/heads/$name。

——quiet意味着没有输出,这很好,因为这样你就可以干净地检查退出状态。 引用/heads/$name限制到本地分支并匹配完整名称(否则dev将匹配develop)

在脚本中的用法:

if git show-ref --quiet refs/heads/develop; then
    echo develop branch exists
fi

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

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

git rev-parse --verify <branch_name>

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

从shell脚本来看,这将是

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