bash Shell脚本检查指定的Git分支是否存在?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21151178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Shell script to check if specified Git branch exists?
提问by hzxu
I need to create a Git branch using shell script, but since the branch may exist, I need to be aware of that. Currently I'm using:
我需要使用 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
But the problem is the grep
command finds branch name without matching the exact name, that is, if I grep name
then branch with a name branch-name
would be matched.
但问题是该grep
命令会在不匹配确切名称的情况下查找分支名称,也就是说,如果我grep name
再branch-name
匹配具有名称的分支。
So is there a better way to do this?
那么有没有更好的方法来做到这一点?
Thanks!
谢谢!
回答by Heath
NOTE: This always returns true. This is not the right answer to the question, even though it has been accepted....
注意:这总是返回 true。这不是问题的正确答案,即使它已被接受......
You could always use word boundaries around the name like \<
and \>
, but instead let Git do the work for you:
您总是可以在名称周围使用单词边界,例如\<
and \>
,而是让 Git 为您完成工作:
if [ `git branch --list $branch_name` ]
then
echo "Branch name $branch_name already exists."
fi
回答by David
I like Heath's solution, but if you still want to pipe to grep, you can use regex anchors, similar to the following, to preclude matching a substring:
我喜欢 Heath 的解决方案,但如果您仍想通过管道传递给 grep,则可以使用类似于以下内容的正则表达式锚点来排除匹配子字符串:
if [ `git branch | egrep "^[[:space:]]+${branchname}$"` ]
then
echo "Branch exists"
fi
Note that you need to use the space
character class because the output of the command is indented.
请注意,您需要使用space
字符类,因为命令的输出是缩进的。