Wednesday, June 8, 2011

Variable Scope - PIPE and WHILE LOOP


The article discusses about the scope of a variable in a While loop (when using PIPE):

Code:

Test="ONE"
echo $Test|while read Test
do
if [ "$Test" = "ONE" ]
then
Test="Two"
echo "INSIDE LOOP :TEST= $Test"
break;
fi
done;
echo "OUTSIDE LOOP :TEST=$Test"

OUTPUT :
INSIDE LOOP :TEST= Two
OUTSIDE LOOP :TEST=ONE

The expected output is "Two" ,but it came as "ONE".
 This is due to the PIPE "|" used in "echo $Test|while read Test".
The PIPE runs the WHILE in a subshell which makes the scope of the WHILE Loop Local
resulting in the OUTPUT "Two".

How to resolve this ?

Code :

Test="ONE"
echo $Test>/tmp/sri.txt
while read Test
do
if [ "$Test" = "ONE" ]
then
Test="Two"
echo "INSIDE LOOP :TEST= $Test"
break;
fi
done </tmp/sri.txt
echo "OUTSIDE LOOP :TEST=$Test"

OUTPUT:
INSIDE LOOP :TEST= Two
OUTSIDE LOOP :TEST=Two

To resolve this, one of the workaround is to gat the date in to file and input the file to the While loop.