kubuzetto
kubuzetto

Reputation: 1096

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?

Upvotes: 5

Views: 3665

Answers (2)

pakistanprogrammerclub
pakistanprogrammerclub

Reputation: 827

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

Upvotes: 4

choroba
choroba

Reputation: 241848

Save the output to a temporary file

tmp=$(mktemp)
make -j4 &> "$tmp"

and only show it if there was an error

if (( $? )) ; then
    cat "$tmp"
fi
rm "$tmp"

Upvotes: 4

Related Questions