How can I selectively check lines for errors (and not fail) when -e
is set.
Most of my commands need -e
, but one does not.
set -e
foo
bar
biz
if [ ! $? -e 0 ]
echo oh noes
fi
The $?
obviously doesn't work.
What is the best way to do this?
From the (4.1) bash
man page for the -e
option:
The shell does not exit if the command that fails is part of the command list immediately following a while or until keyword, part of the test following the if or elif reserved words, part of any command executed in a && or ││ list except the command following the final && or ││
biz || echo "oh noes"
Only if biz
fails does the RHS of the ||
execute, and echo
is guaranteed to exit with status 0 so it cannot cause your script to fail.
You can also run the command with an if
statement, as suggested by Etan:
if ! biz; then
echo "oh noes"
fi
You can also simply turn -e
off temporarily:
set +e
biz
if [ $? -ne 0 ]; then
echo oh noes
fi
set -e
Inline the command running into the if
check.
if ! biz; then
echo oh noes
fi
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.