Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
add comment

2 Answers 2

up vote 2 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).

share|improve this answer
    
Simple and just what I needed. Thanks! –  DaveR9 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 at 0:51
add comment

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"
fi

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}"
fi

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"
ret=$?
if [ $ret -ne 0 ]; then
  echo "script.php failed (status $ret), see the output in $output_file"
fi
share|improve this answer
add comment

Your Answer

 
discard

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.