"set -e" in shell and command substitution
Posted
by
ivant
on Stack Overflow
See other posts from Stack Overflow
or by ivant
Published on 2010-12-30T02:40:24Z
Indexed on
2010/12/30
2:54 UTC
Read the original article
Hit count: 228
shell
|robustness
In shell scripts set -e
is often used to make them more robust by stopping the script when some of the commands executed from the script exits with non-zero exit code.
It's usually easy to specify that you don't care about some of the commands succeeding by adding || true
at the end.
The problem appears when you actually care about the return value, but don't want the script to stop on non-zero return code, for example:
output=$(possibly-failing-command)
if [ 0 == $? -a -n "$output" ]; then
...
else
...
fi
Here we want to both check the exit code (thus we can't use || true
inside of command substitution expression) and get the output. However, if the command in command substitution fails, the whole script stops due to set -e
.
Is there a clean way to prevent the script from stopping here without unsetting -e
and setting it back afterwards?
© Stack Overflow or respective owner