Is it possible to keep the last command exit status ($?) unaltered after a test?
E.g., I would like to do:
command -p sudo ...
[ $? -ne 1 ] && exit $?
The last exit $? should return the sudo exit status, but instead it always returns 0 (the exit code of the test).
Is it possible to do that without a temporary variable?
Another example to clarify further:
spd-say "$@"
[ $? -ne 127 ] && exit $?
In this case i want to exit only if the first command is found (exit code != 127). And i want to exit with the actual spd-say exit code (it may not be
0).
EDIT: I forgot to mention that i prefer a POSIX-complaint solution for better portability.
I use this construct in scripts where i want to provide alternatives for the same command. For instance, see my crc32 script.
The problem with temporary variables is that they could shadow other variables, and to avoid that you must use long names, which is not good for code readability.
if ! command -p sudo; then exit; fiwhich would have the same results for your example. – jordanm Jun 13 '15 at 13:44[ $? -ne 127 ] && exit $?) – eadmaster Jun 13 '15 at 13:47sudocommand succeeds (i.e., ifsudoexits with status 0). But, in your code, the script *keeps running (doesn't exit)* ifsudosucceeds – G-Man Says 'Reinstate Monica' Jun 13 '15 at 14:37commandand notsudoat all. That's what is meant by i want to exit only if the first command is found (exit code != 127) and is a specified return forcommandwhen the command it invokes is not found. I guess the problem is that invokingsudoas part of the test allows forsudosquashing the return ofcommandin the first place and so skewing the test. – mikeserv Jun 14 '15 at 03:15