5" eli...">

Shell: logical AND and OR, not if-else

I was wondering why

i=10
  if [ $i -lt 5 ]; then
    echo "$i < 5"
elif [ $i -gt 5 ]; then
    echo "$i > 5"
elif [ $i -eq 5 ]; then
    echo "$i = 5"
fi

Outputs the correct result:

10 > 5

While

i=10
     [ $i -lt 5 ] && {
    echo "$i < 5"
} || [ $i -gt 5 ] && {
    echo "$i > 5"
} || [ $i -eq 5 ] && {
    echo "$i = 5"
}

behaves unusually:

10 > 5
10 = 5

In my opinion, since the interpreter is looking for 1s, it should work like this:

0 && {} || 1 && {} || 0 && {}

0, so 0 && {} is definitely 0; skip{}

1 means that {} needs to be checked to determine the value of the integer 1 && {}

So, the result is 1, but only {}executed after 1. However, all this works as it should when I put in ! {place of {s.

i=10
     [ $i -lt 5 ] && ! {
    echo "$i < 5"
} || [ $i -gt 5 ] && ! {
    echo "$i > 5"
} || [ $i -eq 5 ] && ! {
    echo "$i = 5"
}

WHY?! I thought he was looking 1, since he finds 0in &&, he does not look at other expressions in the chain!

+4
source share
2

{...} , :

i=10
[ $i -lt 5 ] && 
echo "$i < 5" ||
[ $i -gt 5 ] &&
echo "$i > 5" || 
[ $i -eq 5 ] &&
echo "$i = 5"

:

  • [ $i -lt 5 ]: false ( ), ||, [ $i -gt 5 ] .

  • [ $i -gt 5 ]: ( ), &&, echo "$i > 5", .

  • echo "$i > 5": , &&, echo "$i = 5" .

  • echo "$i = 5": , ... wait no, . .

&& || .

EDIT: ,

A && B || C

if A; then
    B
else
    C
fi

if A; then
    if ! B; then
        C
    fi
else
    C
fi
+5

&& || . :

(((( false && { echo 1; true; } ) || true ) && { echo 2; true; } ) || false ) && { echo 3; true; }
  • false && { echo 1; true; } false
  • false || true true
  • true && { echo 2; true; } 2 true
  • true || false true
  • true && { echo 3; true; } 3 true.

.

+4

All Articles