0

I am new to bash scripting. i wrote a simple code to find the average of all the multiples of ten from 10 to 190 inclusive. The code is:

#!/bin/bash

a=10

ans=0

while[ $a -le 190 ]

do

ans=`expr $a + $ans'
a=`expr $a + 10'

done

echo "$ans"

So what is wrong in this program?

hfarwah
  • 19
  • 2
  • 2
    Try pasting the code in http://www.shellcheck.net/ for the basic errors. Correct them and edit if you still have problems with it. Also, have a read to [How can I add numbers in a bash script](http://stackoverflow.com/a/6348941/1983854). Finally, "isn't working" is not useful: what is not working? what errors do you get? You may want to read [ask]. – fedorqui Apr 26 '16 at 06:19
  • Thanks.Solved the problem. Was a really stupid mistake. :) – hfarwah Apr 26 '16 at 06:21
  • Then provide feedback on what was wrong and, eventually, [write your own answer](http://stackoverflow.com/help/self-answer) about it or accept one of the answers that were provided with a good solution. – fedorqui Apr 26 '16 at 06:24

4 Answers4

1

You have syntax error in your code, try this instead -

#!/bin/bash

  a=10

  ans=0

  while [ $a -le 190  ] 
  do
      ans=`expr $a + $ans`
      a=`expr $a + 10`
  done

  echo "$ans"

Errors you were facing -

  • No space after while
  • Use of ' instead of ` in ans=`expr $a + $ans'
  • Use of ' instead of ` in a=`expr $a + 10'
atefth
  • 1,624
  • 13
  • 26
0

so you have couple of mistakes in your code, this is the correct version of yours:

a=10

ans=0

while test $a -le 190 
do
    a=$(expr $a + 10)
    ans=$(expr $a + $ans)

done

echo $ans

problem was that you have to use test in loops like while or if statements, also for the expr to work you have to put everything in brackets and a dollar sign out of it in the start. The "" in the echo have no use, as long as echo treats them all the same.

Sir. Hedgehog
  • 1,260
  • 3
  • 17
  • 40
0

Your script has some syntax issues. One suggestion you can use "let" instead of "expr" command it makes your code more readable. Ex: let a=10+1. Save your file with executable permission or use "source " to execute.

#!/bin/bash

a=10
ans=0
count=0
while [ $a -le 190 ]; do
    ans=`expr $a + $ans`
    a=`expr $a + 10`
    count=`expr $count + 1`
done

echo "avg: $((ans/count))"
sriramganesh
  • 1,460
  • 1
  • 11
  • 7
-1

It's more efficient to use a closed form solution like this:

lower=10
upper=190
echo $(( ($upper + $lower) / 2 ))
John Zwinck
  • 239,568
  • 38
  • 324
  • 436