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?

2 Answers

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.
2

Yaron's answer helps you understand and remove the syntax errors.

My answer uses some 'nicer' syntax to do the same thing and something else, that might be what you want.

#!/bin/bash read -p "enter a number: " n s=0 i=1 j=0 while [ $i -le $n ] do if [ $(( i % 2 )) -eq 0 ] then s=$(( s + i )) j=$(( j + 1 )) fi i=$(( i + 1 )) # uncomment: remove the '#' from the beginning of the line # echo "i=$i" # uncomment to get debug output done #echo "n=$n" # uncomment to get debug output #echo "j=$j" # uncomment to get debug output #echo "s=$s" # uncomment to get debug output echo "Is this what you want?" echo "sum of $j even numbers ( <= $n ) = $s" echo "or is this what you want?" s=0 for ((i=1;i<=n;i++)) do echo -n "$(( 2*i )) " s=$(( s + 2*i )) done echo "" echo "sum of $n even numbers = $s" 

Running test examples,

$ ./sum-of-even-numbers enter a number: 3 Is this what you want? sum of 1 even numbers ( <= 3 ) = 2 or is this what you want? 2 4 6 sum of 3 even numbers = 12 $ ./sum-of-even-numbers enter a number: 4 Is this what you want? sum of 2 even numbers ( <= 4 ) = 6 or is this what you want? 2 4 6 8 sum of 4 even numbers = 20 $ ./sum-of-even-numbers enter a number: 6 Is this what you want? sum of 3 even numbers ( <= 6 ) = 12 or is this what you want? 2 4 6 8 10 12 sum of 6 even numbers = 42 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy