sunnycoder
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 ?
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
thanks all for the help and suggestions :)
ASKER
will try it out soon