A lot of sh code looks like:
$cmd if [ $? = 0 ]; then $cmd2; fi
Instead of:
if $cmd; then $cmd2; fi
I have typically assumed that people use the former simply because they are unaware that the syntax of the latter is valid, but I'm wondering if there is another reason (although the only possibility that comes to mind is portability). Is there any reason to prefer explicitly referencing ${?}?.
Best Solution
You have to reference
$?
if you actually want to use the error code for something (logging, handling expected errors, etc.). For the particular scenario that you mention, the secondif
construct is both clearer and shorter, and I see no reason not to use it.