'I am getting an error: line 5: conditional binary operator expected ; syntax error near `%' ; line 5: `if [[ $i % 2 = 0 ]]'

Here is my program code: I am getting an error which is: exam.sh: line 5: conditional binary operator expected exam.sh: line 5: syntax error near %' exam.sh: line 5: if [[ $i % 2 = 0 ]]'

#!/bin/bash
i=1;
for user in "$@" 
do
if [[ $i % 2 = 0 ]]
   then
   cd even
   mkdir $user
   .
   else if  [[ $i % 3 = 0 ]]
      then
      cd three
      mkdir $user
      .
      else 
        cd other 
        mkdir $user
   fi 
fi
i=$((i + 1));
done


Solution 1:[1]

[[ doesn't do arithmetics. You need (( for that.

if (( i % 2 == 0 ))

Solution 2:[2]

Another option is to use $((...)) to generate a C-style "boolean" that you can test explicitly.

if [ "$(( x % 2 == 0 ))" = 1 ]; then
    echo "$x is even"
fi

This is objectively worse than if (( x % 2 == 0 )) in bash, but is useful if you need strict POSIX compliance.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 choroba
Solution 2 chepner