You could do (POSIXly):
if { cmd 2>&1 >&3 3>&- | grep '^'>&2; } 3>&1; then echo there was some output on stderrfi
Or to preserve the original exit status if it was non-zero:
fail_if_stderr() ( rc=$({ ("$@" 2>&1 >&3 3>&- 4>&-; echo "$?">&4) | grep '^'>&2 3>&- 4>&- } 4>&1) err=$? [ "$rc" -eq 0 ] || exit "$rc" [ "$err" -ne 0 ] || exit 125) 3>&1
Using exit code 125
for the cases where the command returns with a 0 exit status but produced some error output.
To be used as:
fail_if_stderr cmd its args || echo "Failed with $?"