我想创建一个小型 bash 脚本,检查拉取请求是否从正确的分支启动,如果不是,则出错退出。
这是我发布此问题之前的最后一次尝试/迭代:
if [[ -n $(System.PullRequest.TargetBranch) ]]&&[[ "$(System.PullRequest.TargetBranch)"!="refs/heads/master" ]];
then
echo "$(System.PullRequest.TargetBranch)"!="refs/heads/master"
echo "Branch $(System.PullRequest.TargetBranch) is not master, proceed."
exit 0
fi
if [ -n $(system.pullRequest.sourceBranch) ];
then
if [ "$(system.pullRequest.sourceBranch)"!="refs/heads/hotfixes/"* ]&&[ "$(system.pullRequest.sourceBranch)"!="refs/heads/develop" ];
then
echo "Only hotfixes and develop are allowed to be pulled to the master branch"
exit 1
else
echo "$(system.pullRequest.sourceBranch) is allowed to be pulled to the master branch"
fi
else
echo "variable does not exists"
fi
目前我正在测试/构建此脚本,并且我期望测试用例中有一个退出 1。但我得到了以下输出:
refs/heads/master!=refs/heads/master
Branch refs/heads/master is not master, proceed.
我猜想我在字符串比较语句方面做错了什么(暂且不提稍后的修复 startswith 检查)。但我搞不清楚我做错了什么。我尝试了多种变体,有些给出了其他错误。我不知道接下来该怎么做。
从输出结果可以看出,比较的两个字符串实际上是相同的。所以我不确定哪里出了问题。
答案1
变量和运算符之间需要空格。并且,在此比较中,您不需要使用双括号。
代替
if [[ -n $(System.PullRequest.TargetBranch) ]]&&[[ "$(System.PullRequest.TargetBranch)"!="refs/heads/master" ]];
尝试
target_branch=$(System.PullRequest.TargetBranch) # to simplify the next lines
if [ -n "$target_branch" ] && [ "$target_branch" != "refs/heads/master" ]; then
# ...