Search code examples
bashshellsyntax-error

Bash syntax errors like `syntax error: operand expected (error token is "{1 % 2 ")`


Please tell why printing odd numbers in bash script with the following code gives the error:

line 3: {1 % 2 : syntax error: operand expected (error token is "{1 % 2 ")

for i in {1 to 99}
do
rem=$(( $i % 2 ))
if [$rem -neq 0];
then
echo $i
fi
done

Solution

  • This is working example:

    for i in {1..99}
    do
            rem=$(($i % 2))
            if [ "$rem" -ne "0" ]; then
                    echo $i
            fi
    done
    
    1. used for loop have a typo in minimum and maximum number, should be {1..99} instead of {1 to 99}
    2. brackets of the if statement needs to be separated with whitespace character on the left and on the right side
    3. Comparision is done with ne instead of neq, see this reference.

    As already pointed out, you can use this shell checker if you need some clarification of the error you get.