HOWTO: Make cron not spam you to death.

Sunday, October 14th, 2007

I set up an hourly cron script recently, and got really tired, really fast, of having cron spam me with an execution log when everything was copacetic.

However, while setting up and debugging the script, I was really grateful to get email with the output. Wouldn’t it be nice if there was a way to tell if a command executed properly? Oh, right, exit codes. I modified my script to look something like this:

    OUTPUT=`command1 && command2 && command3;`
    if test "$?" -ne 0; then
        echo $OUTPUT;

Since $? is the exit status of the last command, use && to join your statements, so when one of them fails, you stop right away and don’t drop output on the floor.

Much less evil than my last shell scripting post, and probably much more useful. Thanks to Peter for reminding me how if statements “work” in shell scripts.

Edit: Or as gladium points out in the comments, you can make this a one liner:

    OUTPUT=`command1 && command2 && command3` || echo $OUTPUT



  1. glandium replied on October 14th, 2007:

    Or, in a one-liner: OUTPUT=command1 && command2 && command3 || echo $OUTPUT

  2. Fred Wenzel replied on October 15th, 2007:

    Very useful, thanks!