Ubuntu – Script error: –le: binary operator expected

bashscripts

I'm just starting shell scripting and I got errors trying to execute the follow script:

I have the following script in a script.sh file

echo “enter a value”
read n
s=0
i=0
while [ $i –le $n ]
do
  if [ `expr $i%2` -eq 0 ]
  then
    s= `expr $s + $i `
  fi
  i= `expr $i + 1`
done
echo “sum of n even numbers”
echo $s

Script output:

akhil@akhil-Inspiron-5559:~/Desktop/temp$ chmod 755 script.sh
akhil@akhil-Inspiron-5559:~/Desktop/temp$ ./script.sh
“enter a value”
3
./script.sh: line 5: [: –le: binary operator expected
“sum of n even numbers”
0

What is the source of the error I got?

Best Answer

The source of the error: [: –le: binary operator expected is the fact you are using the unicode version of instead of the regular -

Note: The same apply for the unicode you are using instead of regular "

I've reformat your code to be as follows:

#!/bin/bash
echo "enter a value"
read -r n
s=0
i=0
while [ $i -le "$n" ]
  do
  if [ "$(expr $i%2)" -eq 0 ]
  then
    s=$(expr $s + $i)
  fi
  i=$(expr $i + 1)
done
echo "sum of n even numbers"
echo "$s"

I made the following changes:

  • Replaced the unicode version of chars you used
  • Added #!/bin/bash
  • Deleted space after the = sign
  • Some extra improvements.