Suppress Output Unless Non-Zero Exit Code – Shell Script Tips

cronio-redirectionshell-script

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

quiet_success()
{
  file=$(mktemp)
  if ! "$@" > "$file" 2>&1; then
    cat "$file"
  fi
  rm -f "$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 context, 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.

Best Answer

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
Related Question