Run wget from crontab and only receive errors

If you have tried to run wget from a cron job, perhaps to run your WordPress wp-cron.php, then you will have noticed that whether there is an error or not, then you will still receive a notification at the MAILTO= address configured in your crontab.

This is because wget  annoyingly throws all of its normal output into stderr, so there’s apparently no easy way to only email yourself when wget receives a non 200 response status from the server.

You’ve probably tried this, and found that you still receive an email every time the job runs.

or this, and found you get nothing (because all of the output is black-holed)

Even the -q option isn’t much help because although it will tell you if there is a problem, it won’t provide the verbose output from wget you need to work out what went wrong.

The answer is this


OUT=$((/usr/bin/wget -O /dev/null http://somedomain/someuri >/dev/null) 2>&1) >/dev/null; if [ $? != 0 ]; then echo $OUT; fi

This bit does the actual wget call, and blackhole’s any standard output (not that there should be any, but it’s there for completeness).

This bit redirects the usual output from wget (which goes to stderr, or ‘2’) into stdout, or ‘1’.

Then, the output from wget is stored into the variable OUT. At this stage, the output of wget would still be output to stdout, so we need to blackhole it to prevent anything being output at this stage. Note that by the time this redirection takes place, $OUT has already been assigned with the output from wget.

The next bit simply checks the result status (dollar question) $? from the last executed command, in this case, wget – remember a zero result means no errors, so we are negating this check with != and if the output is non zero then we echo $OUT to stdout (i.e. the console) – this output then gets passed to the cron process, and emailed via the MAILTO= email address.



No comments yet.

Leave a Reply

Time limit is exhausted. Please reload CAPTCHA.