Expr: non-integer argument

This is my code.... It works correct, but does not work with 4 and 5. My program is about finding average. so when i run 4 5 it gives me error "expr: non-integer argument".
But when i say sh average 45 67 it works. Whats wrong?how to fix it?

sum=0
n=0

if [ $# -gt 0 ]
then
for i in $*
do
     if [ -f $i ]
        then
        while read line
              do
              for j in $line
                   do
              n=`expr $n + 1`
              sum=`expr $sum + $j`
                   done
                   done< $i
      else
              sum=`expr $sum + $i`
              n=`expr $n + 1`  
      fi
      done
 else        
      while read line 
      do
      for j in $line
      do
      n=`expr $n + 1`
     sum=`expr $sum + $j` 
     
      done
     done
    fi 
   average=`expr $sum / $n`
     echo $average

I cannot duplicate your problem. Running on Solaris and cygwin under ksh, dash, and bash I get

$> dash -c  './t.shl 4 5'
4

There is one problem - you are only going to get integer answers because expr does integer arithmetic. Normally averages are floating point numbers....

This looks suspiciously similar to a thread from a few days ago: Finding an average.

Is there some reason why the ksh script I provided in that thread can't be used for this?

1 Like