检查指定的 Git 分支是否存在的 Shell 脚本?

41

我需要使用Shell脚本创建Git分支,但由于该分支可能已经存在,所以我需要意识到这一点。目前我正在使用:

if [ `git branch | grep $branch_name` ]
then
    echo "Branch named $branch_name already exists"
else
    echo "Branch named $branch_name does not exist"
fi

问题在于 grep 命令查找分支名称时没有匹配到完全相同的名称,也就是说,如果我执行 grep name,那么名称为 branch-name 的分支也会被匹配到。

那么有更好的方法来解决这个问题吗?

谢谢!


1
已经回答了吗?https://dev59.com/_2435IYBdhLWcg3w3EEi - grebneke
你可以强制grep匹配整行:git branch | grep -E "^$branch_name$" ...或者其他什么。 - stellarhopper
2个回答

66

注意:这总是返回true。 尽管已经被接受,但这不是问题的正确答案....

您始终可以在名称周围使用单词边界,例如\<\>,但是可以让Git为您完成工作:

if [ `git branch --list $branch_name` ]
then
   echo "Branch name $branch_name already exists."
fi

4
如果 [ "git branch --list ${BRANCHNAME}" ],则... - JeffCharter
3
这个句子的意思是“@JeffCharter,这不会总是返回true吗?”。 - Miserable Variable
4
这是一个自动格式问题(反引号被转换为代码标记)if [ "\git branch --list master`" ]; then echo hi; fi`答案实际上总是返回true...这基本上与我的误贴相同。 - JeffCharter
2
在阅读其他链接的答案之前,请不要这样做。简述:git show-ref - Todd Owen
3
解决这个始终返回true的问题可能只需要检查返回的内容不为空:if [ -n "$(git branch --list $branch_name)" ]。尚未经过测试。 - JamJar00
显示剩余3条评论

8

我喜欢Heath的解决方案,但如果你仍然想要管道传输到grep,你可以使用正则表达式锚点来排除匹配子字符串,类似于以下内容:

if [ `git branch | egrep "^[[:space:]]+${branchname}$"` ]
then
    echo "Branch exists"
fi

请注意,您需要使用space字符类,因为命令的输出具有缩进。

5
如果你在分支上,那么开头会有一个星号。这对于匹配命令更为有效,命令为 git branch | egrep "^\*?[[:space:]]+${BRANCH}$" - designermonkey
如果本地不存在该分支,则应验证远程是否存在该分支。使用 git branch --remotes 命令。这里没有当前分支的概念,因此在输出中不会有前导的 *。但是您需要使用带有前缀 origin/ 的分支名称进行搜索 - 即 grep --extended-regexp "^[[:space:]]+origin/${branchname}$" - Martyn Davis
我用自己的存储库进行了测试,包括多个分支。对于非活动分支和不存在的分支名称,它可以正常工作,但是对于活动分支则失败并显示“第8行:[:参数太多”。我完全不懂bash脚本编写,但我发现[ ]是旧式内置测试,并且将“* main” stdin视为2个参数。通过使用新样式测试内置[[ git branch | egrep "^\*?\s+${BRANCH}$ ]],我解决了这个错误。 - pmg7670

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接