Link to home
Start Free TrialLog in
Avatar of sunnycoder
sunnycoderFlag for India

asked on

Updates to variable not visible throughout the script !!!

Came across this problem while answering this question

https://www.experts-exchange.com/questions/20671155/Simple-question-lotsa-points.html

#!/bin/bash

i=0
sum=0
avg=0

ls -l | awk ' { print $5 } ' | while read line
do
    if [ $i -eq 0 ]
    then
         echo -n
          i=1
    else
          sum=`expr $sum + $line`
          avg=`expr $sum / $i`
          i=`expr $i + 1`
    fi
echo $avg
done

echo $avg


This script calculates the average file size in a given directory
In this script, echo $avg inside the while loop prints expected values whereas outside the loop it prints 0 or whatever value I initialize it to before the loop

Can anyone explain why is this so ?
SOLUTION
Avatar of glassd
glassd

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of sunnycoder

ASKER

that is a possibility ...
will try it out soon
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
thanks all for the help and suggestions :)