In ksh shell, I wanna to check the return value after running a command, I’ve wrote two styles:
if [ $? -ne 0 ] ; then
echo "failed!"
exit 1
else
exit 0
fi
[ $? -ne 0 ] && echo "failed!" && exit 1
Are they equivalent? If not, what could I do if I wanna to write it in one line?
They’re close, but not the same. First, the
ifwill execute theexit 1even if theechofailed for some reason; the chained expression won’t. Also, the chained version lacks an equivalent of theelse exit 0.A better equivalent would be this:
This is tagged
ksh, so you might find the numeric expression syntax cleaner:But you can also write an
ifon one line, if you like:If the command that you just ran above this expression in order to set
$?is short, you may want to just use it directly as theifexpression – with reversed clauses, since exit code 0 is true:It doesn’t matter for this simple case, but in general you probably want to avoid
echo. Instead, useprintf– or if you don’t mind being ksh-only, you can useprint. The problem withechois that it doesn’t provide a portable way to deal with weird strings in variables:While both
printfandprintdo:Again, not a problem here, or any time you’re just printing out a literal string, but I found it was easier to train myself out of the
echohabit entirely.