What you're missing is that &&
and ||
operate on exit status of commands to the left of them - left associativity. You have here some group of commands || echo "no"
, and no
will be echoed if and only if that group of commands returns non-success exit status.
What is that group of commands ? In first case you have [ 1 -eq "$1" ] && echo "yes"
. If [
portion failed, that'd be counted as fail exit status for [ 1 -eq "$1" ] && echo "yes"
, therefore you'd echo "no"
would run. Also because of left associativity, when "$1" is 1, the [ 1 -eq $1 ]
returns success, then lets nocmd
run which doesn't exist and shell will return error exit status, the whole group will have exit status of fail, hence `"no" is echoed.
By contrast, in your if statement
if [ 1 -eq $1 ]; then
echo "yes"
else
echo "no"
fi
which route to take depends only on exit status of [
portion. In [ 1 -eq "$1" ] && echo "Yes" || echo "no"
echo also plays role as to whether or not echo "no"
runs.
Your second if statement example is also different
if [ 1 -eq $1 ]; then
nocmd "yes"
if [ $? -ne 0 ]; then
echo "no"
fi
else
echo "no"
fi
The echo "no"
after else
doesn't depend on what happens to nocmd
as in the chaining of logical operators. Sure you still do the echo "no"
part after doing nocmd
, but here its exit status isn't grouped together with the whole if
portion to which it belongs.
./ddd.sh 0
this part will check[ 1 -eq $1 ]
it's not true (false) (1!=0), so this part won't run&& nocmd "yes"
and this part will run|| echo "no"
, but when it's true1=1
it will execute&& nocmd "yes"
part and since shell doesn't recognizenocmd
command, it's reported error.... command not found
and again second part will run|| echo "no"
. – αғsнιη Jan 30 '18 at 17:00