检查指定Git分支是否存在的Shell脚本?
我需要使用shell脚本创建一个Git分支,但是由于该分支可能存在,我需要知道这一点。目前我正在使用:检查指定Git分支是否存在的Shell脚本?,git,bash,shell,grep,Git,Bash,Shell,Grep,我需要使用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命令查找分支名称时没有匹配确切的名称,也就是说,如果Igrep
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
命令查找分支名称时没有匹配确切的名称,也就是说,如果Igrep name
则会匹配具有名称分支名称的分支
那么,有没有更好的方法
谢谢 注意:这总是返回true。这不是这个问题的正确答案,尽管它已被接受
您可以始终在名称周围使用单词边界,如\
,但可以让Git为您完成以下工作:
if [ `git branch --list $branch_name` ]
then
echo "Branch name $branch_name already exists."
fi
我喜欢Heath的解决方案,但如果您仍然希望通过管道连接到grep,则可以使用类似于以下内容的正则表达式锚来排除匹配子字符串:
if [ `git branch | egrep "^[[:space:]]+${branchname}$"` ]
then
echo "Branch exists"
fi
请注意,您需要使用
空格
字符类,因为命令的输出是缩进的。是否已回答?您可以强制grep匹配整行:git branch | grep-E“^\$branch\u name$”…或其他什么。如果您在分支上,那么在开始处有一个星。如果本地不存在分支,则应该验证远程上是否存在该分支。使用git分支--remotes
。没有当前分支的概念,因此此输出中将没有前导的*
。但是您确实需要搜索带有前导的origin/
-即grep--extended regexp“^[:space:]+origin/${branchname}$”
if[“git branch--list${branchname}
”]的分支名称。这不一定是真的吗?这是一个自动格式问题(backtic被转换为代码标记)if[“`git branch--list master``];然后echo hi;fi
答案实际上总是返回true…这与我的mis-post基本相同。请在阅读之前不要这样做。摘要:git show ref
此总是返回true的解决方案可能只是检查返回的内容是否为空:if[-n”$(git branch--列出$branch_name)“]
。但未测试。