0

I want to create a check for when At times this api, does not return anything at all.

myjson=$( curl -X GET "https://api.steampowered.com/ISteamApps/GetAppList/v2/" )

if ( ($myjson | jq '.applist, length' ) > 0); 

then 
    echo $myjson | jq -r '.' > myFile.json

else 
    printf "don't do anything";

fi

I want to check the length of .applist to make sure I don't overwrite the file if it is less 0 (0 would either mean the api is down or some other issue but most importantly it would not update my myFile.json )

if anyone could guide me at what exactly I am doing wrong in the if statement, it would be much appreciated.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441

1 Answers1

0

It's easier here to tell jq to do the numeric comparison itself.

#!/usr/bin/env bash

# exit early if curl failed, no reason to do anything else.
myjson=$(curl --fail \
  "https://api.steampowered.com/ISteamApps/GetAppList/v2/") || exit

if jq -e '(.applist | length) > 0' <<<"$myjson"; then
  echo "There was content returned by the server; updating on-disk file..." >&2
  jq . <<<"$myjson" >myFile.json
else
  echo "There was not content returned by the server; doing nothing" >&2
fi

In terms of exactly what was wrong:

  • if requires a valid shell command to be given as the condition. ( ($myjson | jq '.applist, length' ) > 0) is not a command that does what you want; > 0 is writing output to a file named 0, and $myjson | ... is running your JSON as a command, not feeding it as an input string.
  • echo $anything is buggy; always quote your expansions, as in echo "$anything". See I just assigned a variable, but echo $variable shows something else

Also, note that even this version can leave myFile.json empty or corrupt if the program is interrupted while it's writing content to disk. It's safer to write to a temporary file (on the same filesystem, so the rename is atomic), and rename it over the original only when writing is complete.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • Thanks, would i be right to understand i would need to remove "|| exit" if i had more curl requests being made in the script? I figured, when it created the 0 file i was doing something wrong. I appreciate the clarification that it have to happen within the jq. – Halmy Khozaldy Mar 20 '21 at 02:09
  • If you didn't want the script to exit as a whole, I would move this code into a function, and use `|| return` when you want to abort the function early. – Charles Duffy Mar 20 '21 at 02:52