Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a cron job running a php command like this:

php /path/to/script.php > dev/null

This should send only STDERR output to the MAILTO address. From what I gather the php script is not outputting any STDERR information even when its exit status is 1.

How can I get the output of the php command (STDOUT) and only send it to MAILTO if the exit status is non-zero?

share|improve this question
up vote 9 down vote accepted
php /path/to/script.php > logfile || cat logfile; rm logfile

which dumps standard output into logfile and only outputs it if the script fails (exits non-zero).

Note: if your script might also output to stderr then you should redirect stderr to stdout. Otherwise anything printed to stderr will cause cron to send an email even if the exit code is 0:

php /path/to/script.php > logfile 2>&1 || cat logfile; rm logfile
share|improve this answer
Simple and just what I needed. Thanks! – Dave Dec 5 '12 at 0:38
This will also kick out for anything appearing in stderr, which doesn't necessarily mean there's an error (e.g., debug output). – hoffmanc Jan 4 '14 at 0:51

Since the output is generated before the exit status is known, you'll have to store it somewhere.

One possibility is to store it in a shell variable:

output=$(php /path/to/script.php)
if [ $? -ne 0 ]; then
  printf "%s\n" "$output"

This doesn't completely preserve the script's output (it removes trailing blank lines), but that's ok for this use case. If you want to preserve trailing blank lines:

output=$(php /path/to/script.php; ret=$?; echo a; exit $ret)
if [ $? -ne 0 ]; then
  printf "%s" "${output%a}"

If there's potentially a lot of output, you might prefer to store it in a temporary file instead:

output_file=$(mktemp /var/tmp/script.XXXXXXXXXX.out)
php /path/to/script.php >>"$output_file"
if [ $ret -ne 0 ]; then
  echo "script.php failed (status $ret), see the output in $output_file"
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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