kubuzetto kubuzetto - 3 months ago 10
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

save the output in a variable - and print on error

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