将 while 循环比较存储为变量

store the while loop comparison as a variable

我有以下脚本:

while [[ $(curl test.com/test) != "true" ]];
do
    if [[ $(curl test.com/test) == "stopping" ]] ;then
        /etc/shutdown.sh    # this script will change the output of $(curl test.com/test) to "true"
    else
        sleep $sleep_timer
    fi
done

在这个脚本中,我 运行 $(curl test.com/test) 两次,一次在 while 循环中,一次在 if 语句中。 我不需要 运行 它两次就可以让脚本工作,我想避免它以减少 运行ning 时间,所以我正在寻找一种方法来保存输出第一个 $(curl test.com/test) 作为变量,在以下几行中:

while [[ $(curl_output=$(curl test.com/test)) != "true" ]];
    do
        if [[ $curl_output == "stopping" ]] ;then
            /etc/shutdown.sh    # this script will change the output of $(curl test.com/test) to "true"
        else
            sleep $sleep_timer
        fi
    done

但我不确定这是否可能...

可以use a list in the test-commands portion of the while syntax,把相关的测试命令留到最后;使用该额外命令将内容保存到一个变量中,您稍后可以对其进行测试。

while curl_output="$(curl test.com/test)"; [[ "$curl_output" != "true" ]];
    do
        if [[ "$curl_output" == "stopping" ]] ;then
            /etc/shutdown.sh    # this script will change the output of $(curl test.com/test) to "true"
        else
            sleep "$sleep_timer"
        fi
    done

您不必在循环的条件部分检查 curl 的输出。这样的东西也可以很好地工作:

while true; do
  case $(curl ...) in
  (stopping)
    /etc/shutdown.sh ;;
  (true)
    break
  esac
  sleep "$sleep_timer"
done