I prefer to write solid shell code, so the errexit & nounset is alway set.
The following code will stop at bad_command line
#!/bin/b
A slight variation of the answer given by @rrauenza. Since the && rc=$?
part is their answer will always be equal to && rc=0
one can as well set rc
to 0
before running the command. The result ends up more readable in my opinion because the variable is defined upfront in its own line of code and is only changed if the command exits with a non-zero exit status. If nounset
is also given, then it's now clear that rc
was indeed never undefined. This also avoids mixing &&
and ||
in the same line which might be confusing because one might not always know the operator precedence by heart.
#!/bin/sh
set -eu
rc=0
cat /tmp/doesnotexist || rc=$?
echo exitcode: $rc
rc=0
cat /dev/null || rc=$?
echo exitcode: $rc
Output:
cat: /tmp/doesnotexist: No such file or directory
exitcode: 1
exitcode: 0