Take the tour ×

What's the best way to suppress output (stdout and stderr) unless the program exits with a non-zero code? I'm thinking:

  if ! ( "$@" > "$file" 2>&1 ); then
    cat "$file"

And run quiet_success my_long_noisy_script.sh but I'm not sure if there's a better way. I feel like this has to be something other people have needed to do.

For the record, I'm looking to add this to my cron scripts, so that I get emailed with everything if they fail, but not if they don't.

share|improve this question
This should be the default behavior of most commands (no output on success). If not, the first thing to do is to look for an option / switch to enable such behavior. Failing that, your approach is the right idea. Side note: I'm assuming you posted pseudo-code because it is not actually valid sh syntax, and your redirection order is backwards (do > "$file" 2>&1 and use more quotes). –  jw013 Jun 22 '12 at 14:50
Yep, I just typed it up in the question. Applied your suggestion, and I agree, the command should be responsible for that, but alas... –  dimo414 Jun 22 '12 at 14:53
Just a syntax note: no need for parenthesis around the command. –  manatwork Jun 22 '12 at 16:27
add comment

1 Answer

up vote 5 down vote accepted

You're going to have to buffer the output somewhere no matter what, since you need to wait for the exit code to know what to do. Something like this is probably easiest:

$ output=`my_long_noisy_script.sh 2>&1` || echo $output
share|improve this answer
add comment

Your Answer


