kubuzetto kubuzetto - 1 year ago 37
Linux Question

In bash, how can I display the output of a command ONLY if there is an error?

I have a build script in which, at some point, I call

make -j4
. I don't want to see its entire output every time, though; except when there is an error. So how can I buffer the output of make and print it if it returns a non-zero result?

Answer Source

save the output in a variable - and print on error

cmdout=$(make -j4 2>&1)
if ((es)); then
  echo >&2 "make error es $es: \"$cmdout\""
  echo "make success"