How to keep last exit status after test
There are various options to handle the exit status reliably without overhead, depending on the actual requirements.
You can save the exit status using a variable:
command -p sudo ...
rc=$?
[ "$rc" -ne 1 ] && echo "$rc"
You can directly check success or failure:
if command -p sudo ...
then echo success
else echo failure
fi
Or use a case
construct to differentiate the exit status:
command -p sudo ...
case $? in
(1) ... ;;
(127) ... ;;
(*) echo $? ;;
esac
with the special case asked in the question:
command -p sudo ...
case $? in (1) :;; (*) echo $?;; esac
All those options have the advantage that they are conforming to the POSIX standard.
(Note: For illustration I used echo
commands above; replace by appropriate exit
statements to match the requested function.)
command -p ...
test 1 -ne $? && exit $_
Use $_
, which expands to the last argument of the previous command.
You can define (and use) a shell function:
check_exit_status()
{
[ "$1" -ne 1 ] && exit "$1"
}
Then
command -p sudo ...
check_exit_status "$?"
Arguably, this is "cheating",
since it makes a copy of $?
in the check_exit_status
argument list.
This may seem a little awkward, and it is.
(That sometimes happens when you impose arbitrary constraints on problems.)
This may seem inflexible, but it isn't.
You can make check_exit_status
more complex,
adding arguments that tell it what test(s) to do on the exit status value.