Quote:
Originally Posted by
jfxdavies
If I use the following:
[ $? != 0 ] && echo "echo failed"
$? returns 1
When I use
if [ $? != 0 ] ; then echo "echo failed" ; fi
$? returns 0
Does anyone know what's wrong with this?
There is nothing wrong. What you are seeing is correct behavior. In each case you are seeing the exit status of the last command to run.
In the first case, the last command before echoing $? is
[ $? != 0 ]. The test failed and so $? is set to 1.
In the second case, you're seeing the exit status of the if-statement itself. Since the conditional test fails, the if-statement does not execute further, the list of commands after
then does not execute. So the if-statement itself sets $? to 0.
That following quote is from
POSIX: Shell Command Language, but your KSH man page should contain similar text.
Quote:
The exit status of the if command shall be the exit status of the then or else compound-list that was executed, or zero, if none was executed.
Regards,
Alister