or in a IF condition

Hi
I have to evaluate multiple conditions with an 'or'.

Here is an example:

if [ $connect == "n" || $connect == "N" ]

when i use the above i get a error message
[: missing `]'

Please help me to know if i am missing something in the syntax.
how do i achieve multiple "or" in the same if condition.

Thanks.

if [ "$connect" == 'n' -o  "$connect" == 'N' ]
1 Like
if [ "$connect" = n ] || [ "$connect" = N ] ; then
...
fi
case $connect in
  N|n ) ... ;;
esac 
1 Like

Thanks folks.
It helped me.
One last question in the same context.
Can i have multiple condition checks in the same IF.
example:

if [ cond1 -o cond2 -o cond3 -o cond4 ......]

I tried the above but i am not able to get it working.
Please can you help to understand if i can achieve multiple condition checks as stated above.

Thanks.

Please post the actual script, explaining what is not working.

The POSIX standard does not say what would be the result of test or `[' when there are more than four arguments. It might or it might not work.
If you want portable sure thing, use several test or the && with `['

Also, -o and -a are considered obsolescent, the preferred way is to use multiple tests with && or || .
POSIX specification: test: APPLICATION USAGE

2 Likes

Hmm another example of daft Posix ideas.
To my mind the "-o" and "-a" syntax is easier to follow - expecially when bracketed for clarity. However if you happen to be a "C language" programmer you may disagree.

But ... a "case" statement may take more time to type but is a much more readable for the next person to read your script.

if [$connect == "n" -o $connect == "N" -o $connect == "no" -o $connect == "No" -o $connect == "NO"]
then

echo "i am in N"

else
echo "i am in Y"

fi

You need spaces around the square brackets and you need weak quotes around the variables. Try this:

if [ "$connect" = n -o "$connect" = N -o "$connect" = no -o "$connect" = No -o "$connect" = NO ]; then

or preferrably this:

if [ "$connect" = n ]||[ "$connect" = N ]||[ "$connect" = no ]||[ "$connect" = No ]||[ "$connect" = NO ]; then

I would use a case statement;

case $connect in
  n|N|no|No|NO)
    echo "i am in N" ;;
  *)
    echo "i am in Y" ;;
esac
1 Like

@Scrutinizer In both cases the above syntax will only work with bash.
In unix "Posix" shells there is no "==" operator.
I agree that the "case" solution is the best.

1 Like

You are right :b:, I overlooked the double == . It should be single = everywhere... I corrected my post...