I have some simple smoke test scripts that generally look like:
set -e
run-command
run-other-command
echo ok
This works great when I expect commands to succeed; if any fails, the set -e
will exit the script early with a non-zero exit code.
However sometimes I expect a command to fail, and I want the script to exit otherwise (that is, if the command exits with code 0). I would have thought I could just write:
set -e
run-command-that-succeeds
! run-command-that-fails
But this ignores the exit code. The bash man page says this about set -e
:
The shell does not exit [...] if the command's return value is being inverted with !
Alternatives that work are:
set -e
! run-command-that-fails
[[ $? -eq 0 ]]
and
set -e
if run-command-that-fails; then
exit 1
fi
Are these the best options, or is there a more idiomatic alternative to exit if a command succeeds?