Multiple conditions inside my if statement

Hello,
I am using shell scripting and I am recieving odd results from my if statement

     if [ $L1 -eq 0 -a $L2 -eq 1 -o $L2 -eq 2 -o $L2 -eq 3 ]

I want it to enter the loop only if L1 is equal to zero and one of the other criteria are filled, however it is entering at other times as well. What can i do to fix this? i tried seperating it like in matlab, but im not sure how to get it to correctly do what i am trying.

That it because you should make the first if as a condition, then the others...

if  [ $L1 -eq 0  ]
then
     if [ $L2 -eq 1 -o $L2 -eq 2 -o $L2 -eq 3 ]
     then
          blah
          blah
    fi
fi
1 Like

great that worked thank you!

Try this...

#!/bin/bash

L1=0
L2=1

if [[ $L1 -eq 0 ]] && [[ $L2 -eq 1 || $L2 -eq 2 || $L2 -eq 3 ]]
then
    echo "True"
else
    echo "false"
fi

It's a matter of operator precedence: -a has higher p. than -o. So it's (expr1 AND expr2), OR expr3, OR expr4. You can overrule this using parentheses which, unfortunately, must be escaped in bash:

 if [ "$L1" -eq 0 -a \( "$L2" -eq 1 -o "$L2" -eq 2 -o "$L2" -eq 3 \) ]; then echo "yes"; else echo  "no"; fi

This will work as you expected.

You can easily simplify that into one expression:

if [ "$L1" -eq 0 -a "$L2" -ge 1 -a "$L2" -le 3 ]

And here is how I usually write it

if [ "$L1" -eq 0 ] && [ "$L2" -eq 1 -o "$L2" -eq 2 -o "$L2" -eq 3 ]; then ...

works in both sh and bash
Almost the same as @itkamaraj