1

I am writing a shell script to calculate the averages of numbers from a file but for some reason bash is not adding my numbers together.

I have tried multple ways of formatting the sum='expr $sum + $num' but keep getting errors.

while read line
do  
    sum=0
    count=0
    average=0
    median=0

    #read each line, sort it and put it into tempRows file
    echo "$line" >> $tempRow
    sort $tempRow

    #add each number to the sum for avg calculation
    for i in $tempRow
        do
        num=$i
        count=`expr $count + 1`
        echo "count: $count"
        sum=`expr $sum + $num`
        echo "sum: $sum"    
        done

    #perform and print average calc at the end of each line
    average=`expr $sum / $count`

    echo -e "$average\t"

    rm -f $tempRow
done < $tempFile

Currently this code gives me following output before quitting

count: 1
expr:non-numeric argument
sum:
expr:syntax error

I am sorting each line before adding to tempRow for a later median calculation A sample file would contain multiple rows and columns of whole numbers and I would print out each rows average and median

1
  • You should register one of your accounts so that you can edit your own question.
    – Jeff Schaller
    Commented Jan 31, 2017 at 1:52

1 Answer 1

4

Run bash -x myscript. That'll give you a trace of the execution which should make the problems clear.

Your main problem is

for i in $tempRow

The variable $tempRow contains a file name. Assuming that the name of the file does not contain any whitespace or wildcard characters, $tempRow expands to a list of one word which is that file name. So the for loop body runs once, with i set to the name of the file.

It appears that you wanted to iterate over the lines of the file. Use while read for that. Or rather, while IFS= read -r i; do ….

Some additional tips:

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .