Saturday, October 6, 2012

Shell script, scope of variables

recently I was maintaining shell scripts written in a very sloppy way by a (luckily) gone consultant.
First, the standard way of reading the content of a file in shell scripts is:
counter=0
while read line 
do
   echo $line
   counter=`expr $counter + 1`
done < myfile.txt
echo $counter


For some funny reason (arrogance and ignorance) the consultant had instead written:
cat myfile.txt | while read line 
do
   echo $line
   counter=`expr $counter + 1`
done
echo $counter



The big problem with pipes is that they are executed in a subshell, and they don't access the same variable space of the main shell.... so the above code will always print 0 (zero) as the value of the counter.
No workaround found so far. Just don't use pipes.

No comments: