Skip to content
Advertisement

Bash: syntax error operand expected “=”, in assignment statement in a for loop

EDIT: I think that it’s not picking up the $1 as the operand. I tried storing it in a variable, then trying the assignment but it seems that has no effect.

EDIT 2: provided a minimal reproducible script as requested.

The error generating part of the code is the following:

check() {
if [ $1 -lt $2 ]; then
 for((var=$1; var<$2; var++)); do
  if [ $((var%2)) -eq 0 ]; then
   echo "it's an even number"
   fi
  done
fi
}

if [ $# -eq 2 ]; then 
check
fi

the rest of the function’s code will be attached below. The function is rather long to re-type out; I’m using ubuntu through a VM which doesn’t allow for items to be copied into or pasted out of the VM, but this just may be a settings thing.

part 1 of the function

part 2 of the function

Advertisement

Answer

You are invoking your function by

check

i.e. you don’t pass any parameter, Hence, $1 and $2 are empty, so this can’t work. You would have to write

check "$@"

or

check "$1" "$2"

depending on what exactly you want to achieve.

However, with your original code, you should then get for your if statement an error message

[: -lt: unary operator expected

UPDATE: As GordonDavisson pointed out in his comment, you won’t get this syntax error here, because both operands are missing in your case and -lt then looses its meaning of being treated as operator.

BTW, if you had written the test as

if (( $1 < $2 )); then

you would have received a syntax error (bash: ((: < : syntax error: operand expected (error token is “< “))

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement