I have script
#!/bin/bash
set -e
if [[ ! $(asd) ]]; then
echo "caught command failure with exit code ${?}"
fi
echo "end of script"
purpose of script is to terminate execution on any non zero command exit code with set -e
except when command is "caught" (comming from Java) as in case of bad command asd
if [[ ! $(asd) ]]; then
echo "caught command failure with exit code ${?}"
fi
however, though I "catch" the error and end of script
prints to terminal, the error code is 0
echo "caught command failure with exit code ${?}"
so my question is how can I "catch" a bad command, and also print the exit code
of that command?
edit
I have refactored script with same result, exit code is still 0
#!/bin/bash
set -e
if ! asd ; then
echo "caught command failure with exit code ${?}"
fi
echo "end of script"
只需使用短路:
asd || echo "asd exited with $?" >&2
how can I "catch" a bad command, and also print the exit code of that command?
Often enough I do this:
asd && ret=$? || ret=$?
echo asd exited with $ret
The exit status of the whole expression is 0
, so set -e
doesn't exit. If asd
succedess, then the first ret=$?
executes with $?
set to 0
, if it fails, then the first ret=$?
is omitted, and the second executes.
Sometimes I do this:
ret=0
asd || ret=$?
echo asd exited with $ret
which works just the same and I can forget if the &&
or ||
should go first. And you can also do this:
if asd; then
ret=0
else
ret=$?
fi
echo asd exited with $ret
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.