首页 > 解决方案 > 如何使用 bash 将 if then 语句添加到具有多个参数的值

问题描述

我在我的 TMP 位置存储了 2 个值:{time_total}{http_code}

我想添加一个 if-then 条件来检查状态。如果它不是 100,我希望它打印出一行“出了点问题”。但如果值等于 100,则不显示任何内容。

echo getInfo  >> $SAVE_TO
for i in "${LB[@]}"
   do
        TMP=$(curl  -X GET -sS -w "%{time_total},%{http_code}\n" -H "UNAME:  
$USER" -H "UPASS: $PWD" -H "Content-Type: application/json"  -d '{"propertytosearch":"systemUserName", "systemUserName":"XXXXXXX"}' https://$i/ws/rest/v2/getInfo -o /dev/null)
        echo ,$i,$TMP >> $SAVE_TO
   done

if [[ $http_code != $200 ]]
then
 echo "something wrong with $i"
fi

TMP 输出:

1.207,100

如果我删除%{time}并仅使用%{status},则 if-then 命令有效。我将如何处理 2 个输入值?

我不一定需要检查{time},但如果需要,我可以有一个 if 条件来检查任何大于 4.000 的时间。它可以有相同的回声“出了点问题”。

标签: bashif-statement

解决方案


要读取两个单独的变量timestatus您可以执行以下操作:

IFS=, read -r time status < <(curl  -X GET -sS -w "%{time},%{status}\n" -H)

...之后,您可以单独测试它们:

if [[ $status != 100 ]]; then  # note that $status is safe unquoted only in [[ ]], not [ ]
  echo "Something is wrong"
fi

推荐阅读