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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 00:37:26  来源:igfitidea点击:

Shell script to check if specified Git branch exists?

gitbashshellgrep

提问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 grepcommand finds branch name without matching the exact name, that is, if I grep namethen branch with a name branch-namewould be matched.

但问题是该grep命令会在不匹配确切名称的情况下查找分支名称,也就是说,如果我grep namebranch-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 spacecharacter class because the output of the command is indented.

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