0

I'm running Ubuntu and got a simple cronjob fetching a remote JSON-file and (over)writing it to the server.

*/15 * * * * /usr/bin/curl -m 120 -s https://path/to/remote/json.json > /store/json/here.json

However I need to make sure the external JSON actually returns data before it overwrites the JSON file located on the server.

How can I achieve this? I've found some ways to do it straight in bash, but doesn't seem to work when I put in the crontab.

  • 1
    create a script that would do it and use the script in crontab instead. – Bart Jun 25 at 13:15
1

Write a short shell script and call the script from your crontab.

The script may look something like

#!/bin/sh

PATH=/usr/bin:$PATH

cd /store/json || exit 1

if curl -m 120 -s https://path/to/remote/json.json >here.json.tmp &&
    [ -s here.json.tmp ]
then
    mv here.json.tmp here.json
else
    rm here.json.tmp
fi

The -s test is true if the given file has a size greater than zero.

  • 1
    also consider using the return status from curl. – ctrl-alt-delor Jun 25 at 14:37
  • @ctrl-alt-delor Thanks. Fixed. – Kusalananda Jun 25 at 15:19
  • I was thinking of using the return status, to determining if it was successful. Why replace the file if not successful. – ctrl-alt-delor Jun 25 at 16:38
  • @ctrl-alt-delor Ah, sure. I used sh -e in my first version, to terminate if anything failed. That would potentially have left the temporary file around I realise now. I'll rewrite it the way I think you mean. – Kusalananda Jun 25 at 18:07
  • Ahh. Yes terminate on error should do it. – ctrl-alt-delor Jun 25 at 19:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.