print-if-error shell

cron is a very nice and useful tool. it has a bit annoying mailing policy – it sends e-mail each time something is output on the screen, by the task being executed. in u*ix silence is gold. however there are commands that do no obey this rule (ex. gnu/make), mix stdout with stderr (ex. unix2dos), and so on… this is annoying, since each time job executes it sends an e-mail you're not really interested in. to silence bastard you need to redirect stdout and stderr to /dev/null. but wait! what if there actually IS a problem? what if your backups are no longer executing nightly? well – you'll never find out.

even if you discard only stdout, you still might be missing some context information, in case some script is more verbose by nature. when scripting it is often much easier to handle errors by aborting shell, and pointing out what's going on in case of longer running ones by echoing non-error messages. so in fact you're loosing some pieces of information.

solution

being sick and tired of this i've decided to write a wrapper to handle this. rules are simple:

  1. mail should be sent ONLY if the command returned an error.
  2. mail should contain the full output of the command.

wrapper script has been named printiferror – pretty self-explaining. :)

the initial solution used syntax for taking command and its arguments as parameters (the way time or exec commands do). the original crontab:

# ...
31 2 * * 0   ionice -c 3 nice make-backup --full
31 2 * * 1-6 ionice -c 3 nice make-backup --inc
# ...

evolved to:

# ...
31 2 * * 0   /usr/local/bin/printiferror ionice -c 3 nice make-backup --full
31 2 * * 1-6 /usr/local/bin/printiferror ionice -c 3 nice make-backup --inc
# ...

script works like a charm! what it does is save stdout and stderr in a temporary file and in case command fails, it prints output of that file on the console. this way cron mails only if the script fails.

solution 2.0

it is annoying to put printiferror command in front of all cron jobs. it is also error prone, by design (if you forget, by the morning you can end up with dozens of spam messages). this is why i went a step ahead – i've made this script behave as if it was a shell! thanks to this syntax using it is plain simple – one extra line in the crontab and we're done:

SHELL=/usr/local/bin/printiferror
# ...
31 2 * * 0   ionice -c 3 nice make-backup --full
31 2 * * 1-6 ionice -c 3 nice make-backup --inc
# ...

and voila! no spam, and in case of error, you get full messages.

download

you can download and use printiferror for free – enjoy. :)

prjs/print-if-error_shell.txt · Last modified: 2021/06/15 20:09 by 127.0.0.1
Back to top
Valid CSS Driven by DokuWiki Recent changes RSS feed Valid XHTML 1.0