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

    #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
        count=`expr $count + 1`
        echo "count: $count"
        sum=`expr $sum + $num`
        echo "sum: $sum"    

    #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
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

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

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:

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.