bashshell

Shell script for reading the response from curl and looping on a particular value from the JSON response


I am creating a shell script(.sh) and trying to read a particular value from the JSON response from a REST call. Below is the sample json response which I get by calling a Rest URL(GET)

{"isTestRunning":false,"status":null}

Here is the logic I am trying to code in shell script. I am completely new to the shell scripting and finding it difficult to script for my requirement. How do I have to start on this? If anyone of you have a documentation link will also be very helpful?

response = curl 'http://test-url/checkTestEnable'
for(till response.isTestRunning is true)
{
  response = curl 'http://test-url/checkTestEnable'
   if(response.isTestRunning is false){
    //curl 'another url'
    //break the loop.
   }

}

Solution

  • I would go with jq for that. jq is like sed for JSON data.

    while [ "$(curl -sS -H 'Accept: application/json' 'http://test-url/checkTestEnable' |
               jq '.isTestRunning')" = "true" ]; do
      sleep 10
    done
    curl 'ANOTHER_URL'
    

    If jq isn't available you can use the following, somewhat ugly regular expression with sed instead.

    while [ "$(curl -sS -H 'Accept: application/json' 'http://test-url/checkTestEnable' |
               sed -re 's/.*":(false|true),".*/\1/')" = "true" ]; do
      sleep 10
    done
    curl 'ANOTHER_URL'
    

    BTW: If you can create shell scripts, then you can install jq, it's just a single binary.