【问题标题】:how to use value of curl in while loop?如何在while循环中使用curl的值?
【发布时间】:2020-09-01 15:02:58
【问题描述】:

即使状态变为“UP”,也将继续。为什么我不能在循环中使用变量作为条件?

export confup=false
export blup=false
timeout 30 bash <<EOF || false
while [[  $( curl http://0.0.0.0/ | jq -r '.status') != "UP" ]];
do
if [[ $( curl http://0.0.0.0/ | jq -r '.components."bridge.lock".status') == "UP" && \$blup == "false" ]]; then
    echo "true
    export blup=yes
fi
if [[ $( curl http://0.0.0.0/ | jq -r '.components."Configuration converted".status') == "UP" && \$confup == "false" ]]; then
    echo "true"
    export confup=yes
fi
echo $( curl "http://0.0.0.0/" | jq -r '.status')
sleep 5
done 
EOF

【问题讨论】:

  • 除了 Barmbar 的正确答案之外,我看不出您为什么要使用 here-DOC 的充分理由。它只会使事情变得不必要地复杂化,并使您的代码更难维护。顺便说一句,由于您将 here-DOC 作为子进程运行,因此您对 blupconfup 的更改将不会在您的(父)脚本中可见。

标签: bash while-loop


【解决方案1】:

您不是每次都在循环中执行curl。它只是被执行一次,结果被替换到 here-doc 中。

您应该使用引用的 here-doc,这样变量和命令替换就不会在原始文档上进行。那么你也不需要在$blup$confup中转义$

也不需要导出这些变量。

timeout 30 bash <<'EOF' || false
while [[  $( curl http://0.0.0.0/ | jq -r '.status') != "UP" ]];
    do
    if [[ $( curl http://0.0.0.0/ | jq -r '.components."bridge.lock".status') == "UP" && $blup == "false" ]]; then
        echo "true"
        blup=yes
    fi
    if [[ $( curl http://0.0.0.0/ | jq -r '.components."Configuration converted".status') == "UP" && $confup == "false" ]]; then
        echo "true"
        confup=yes
    fi
    echo $( curl "http://0.0.0.0/" | jq -r '.status')
    sleep 5
done 
EOF

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-06
    • 2015-01-08
    • 1970-01-01
    相关资源
    最近更新 更多