如何比较shell脚本中的两个字符串与IF条件

How to compare two strings in shell script with IF condition

提问人:narasimman bala 提问时间:10/6/2023 最后编辑:Barmarnarasimman bala 更新时间:10/6/2023 访问量:50

问:

当我在 shellscript 中使用 IF 条件比较两个字符串时,我没有得到预期的结果。

这是事件日志,在我们的应用程序中看起来像。 我将其分配给 executionstatus。

"composite_status": "deployed",
   "name": "Eventing-Function",
   "num_bootstrapping_nodes": 0,
   "num_deployed_nodes": 5,
   "deployment_status": true,
   "processing_status": true,
   "redeploy_required": false 

"composite_status": "deployed",
   "name": "Eventing-Function-on-expiry",
   "num_bootstrapping_nodes": 0,
   "num_deployed_nodes": 5,
   "deployment_status": true,
   "processing_status": true,
   "redeploy_required": false
 
"composite_status": "deployed",
   "name": "Eventing-Function-dev",
   "num_bootstrapping_nodes": 0,
   "num_deployed_nodes": 5,
   "deployment_status": true,
   "processing_status": true,
   "redeploy_required": false 

通过上述内容,我们进一步将“deployed”分配给 status,将 name 字符串以及 name 变量分配给 name。我们有一组 5 个节点运行 for 循环。

要求是我想检查上述三个事件函数的状态是否已部署,如果没有,它应该触发邮件警报。所以我正在检查与字符串$status与 $cbstatus 匹配的 IF 条件,但我得到了这个。我想我在这里错过了一些东西。请帮忙整理一下。

输出

+ '[' 'deployed deployed deployed ' == 'deployed deployed deployed' ']'
+ echo 'status is not deployed at ' $url

脚本:

for url in "${uat_urls[@]}"
do
    executionstatus=$(curl -sX GET -u ${admin}:${password} 'http://'${url}':8009/api/v1/status')
    status=$(echo $executionstatus | grep -o '"composite_status": "[^"]*'| grep -o '[^"]*$' |tr '\n' ' ')
    name=$(echo $executionstatus | grep -o '"name": "[^"]*'| grep -o '[^"]*$')

    cbstatus=$(printf "deployed deployed deployed")
    echo $status
    echo $cbstatus
    if [ "${status}" != "${cbstatus}" ]; then
        echo "status is not deployed at " $url  >> status.txt
        # mail that the eventing function is not deployed
        echo "$(<status.txt )" | mailx -r "xyz.testcom" -s "FE CB AS eventing service status" $mail_me
        rm status.txt
    else
       echo "status is not deployed at " $url >> status.txt
    fi
Linux Bash shell for-loop if-语句

评论

0赞 Cyrus 10/6/2023
请查看如何使用 Markdown 或 HTML 格式化我的帖子?
1赞 Barmar 10/6/2023
第一个字符串的末尾有一个额外的空格。
0赞 Barmar 10/6/2023
您正在将换行符转换为空格。由于在每行输出后放置一个换行符,以空格结尾。grep$status
0赞 Barmar 10/6/2023
因此,要么删除尾随空格,要么在 的末尾添加一个空格。$status$cbstatus
1赞 Walter A 10/6/2023
删除尾随空格:if [ "${status% }" != "${cbstatus}" ]; then

答: 暂无答案