Multiple If statements in bash problem

Hi everyone,

May you help me with the correct syntax of the follow bash statements please

X=10
if [[ "$X" <= 5 ]]; then
    echo "The value is between 1 and 5"
    for ((i=1;i<=${X})); do
     echo $i
    done 
else if [[ "$X" > "5" && "$X"<= 10 ]]; then
    echo "The value is between 6 and 10"
    for ((i=1;i<=${X})); do
     echo $i
    done 
else if [[  "$X" > 10 )) &&  "$X" <= 20]; then
    echo "The value is between 10 and 20"
    for ((i=1;i<=${X})); do
     echo $i
    done 
fi

Thank in advance

You have not mentioned the error messages.
At the first look,

for integer values comparison, You should you -lt type syntax.

-lt => less than
-le => less than or equal
-gt => greater than
-ge => greater than or equal
-eq => equal
-ne => not equal

There must be a white space on both side of comparison operator and square brackets.

e.g

[ "$X" <= 20] #invalid
["$X" <= 20 ] # invalid
[ "$X"-le 20] # invalid
[ "$X" -le 20 ] #valid

Hi anchal_kare,

I receive syntax errors. I've tried both ways, like in my first post and using comparison operators as you suggest me.

X=10
if [[ "$X" -le 5 ]]; then
    echo "The value is between 1 and 5"
    for ((i=1;i<=${X})); do
     echo $i
    done 
else if [[ "$X" -gt 5 && "$X" -le 10 ]]; then
    echo "The value is between 6 and 10"
    for ((i=1;i<=${X})); do
     echo $i
    done 
else if [[  "$X" -gt 10 &&  "$X" -le 20 ]]; then
    echo "The value is between 10 and 20"
    for ((i=1;i<=${X})); do
     echo $i
    done 
fi

But I continue receiving syntax errors
-syntax error near of unexpected element "fi"

  • it requires an arithmetic expression
  • syntax error near of ";"

Thanks for your help

And the error is that X is 10, and loop won't run since X never changes.

You have also loop errors

for ((i=1;i<=${X}));

Should be i guess

 for ((i=1;i<=${X}; i++));

Also a syntax error:

else if [[  "$X" > 10 ))

Guessing it should be

else if [ $X -gt 10 ] ..

else if should be elif

1 Like

Thanks itkamaraj,

Even when I had some other errors, that's was the main problem.

The correct syntax as I want is:

X=17
if (( "$X" <= 5 )); then
    echo "The value is between 1 and 5"
    for ((i=1;i<=${X};i++)); do
     echo $i
    done 
elif (( "$X" > 5 )) && (( "$X" <= 10 )); then
    echo "The value is between 6 and 10"
    for ((i=1;i<=${X};i++)); do
     echo $i
    done 
elif (( "$X" > 10 &&  "$X" <= 20 )); then
    echo "The value is between 10 and 20"
    for ((i=1;i<=${X};i++)); do
     echo $i
    done 
fi

Thanks again to all for your help.

Regards