Home > Blockchain >  store the while loop comparison as a variable
store the while loop comparison as a variable

Time:10-09

I have the following script in place:

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

In this script, I run $(curl test.com/test) twice, once in the while loop, and once in the if statement. I don't need to run it twice for the script to work, and I would like to avoid it to reduce the running time, so I'm looking for a way to save the output of the first $(curl test.com/test) as a variable, something in the lines of:

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

But I'm not sure if it's possible...

CodePudding user response:

You can use a list in the test-commands portion of the while syntax, leaving the pertinent testing command for last; use that extra command to save the contents to a variable that you can test against later.

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

CodePudding user response:

You don't have to examine curl's output in the condition part of the loop. Something like this would work perfectly fine as well:

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