Search code examples
pythonlinuxshellcurlcommand

Shell one liner custom curl command with if else handling


I'm trying to read a url using curl command, and expecting command to exit with return code 0 or 1 based on response of curl after parsing the response json.

I tried to parse a json response, but notable to make it working in if else condition.

URL - localhost:8080/health

response of the url

{
    "db": {
        "status": "healthy"
    },
    "scheduler": {
        "fetch": "2024-03-12T04:32:53.060917+00:00",
        "status": "healthy"
    }
}

Expected output - one liner cmd to return with exit code 0 if scheduler.status is healthy else 1

Note - I'm not looking for curl response as 0 or 1 but looking for command to exit with 0 or 1.

Purpose - If my scheduler status is unhealthy than my process would terminate and exit from the app.

I'm able to parse the response message but notable to apply condition properly on response here is what i tried so far,

cmd 1 :

if ((status=$(curl -s 'https://localhost:8080/health' | python -c "import sys, json; print (json.load(sys.stdin) ['scheduler'] ['status'])"))='healthy'); then exit 0; else 1;

It throws error as.

zsh: parse error near `='healthy''

From above cmd this curl -s 'https://localhost:8080/health' | python -c "import sys, json; print (json.load(sys.stdin) ['scheduler'] ['status'])" part is working fine returns (healthy/unhealthy) while adding condition failing.

cmd 2:

/bin/sh -c "status=$(curl -kf https://localhost:8080/health --no- progress-meter | grep -Eo "scheduler [^}]" | grep -Eo '[^{]$' | grep -Eo "status [^}]" | grep -Eo "[^:]$" | tr -d \"' | tr -d '\r' | tr -d '\ '); if [ $status=='unhealthy']; then exit 1; fi;0"

This is also not working but, this part curl -kf https://localhost:8080/health --no- progress-meter | grep -Eo "scheduler [^}]" | grep -Eo '[^{]$' | grep -Eo "status [^}]" | grep -Eo "[^:]$" | tr -d \"' | tr -d '\r' | tr -d '\ ' is working fine to return healthy/unhealthy

I tried all this short of, but no luck not sure if there is any workaround with a single cmd.

great if there is any option using shell without python else with python would also work

Please note - No Jq or any other tool installation is required, just with existing commands


Solution

  • When you know you don't have a '}' in your health variables, you can use

    curl -s 'https://localhost:8080/health' | tr -d '\n' | grep -Eq '"scheduler": [^}]*"healthy"'