I am writing a shell script using the korn shell. It seems that I am only
able to use local variables within a while loop that is reading a file.
(I can't access a variable outside a previously used while loop.) It's been
a while since I wrote shell scripts. Here is a sample
cat file.txt
foo
bar
ksh script
#!/bin/ksh
count=1
cat file.tx | while read var; do
echo $count
count=$((count+1))
done
echo Value outside loop
echo $count
Exit script
1
2
3
Value outside loop
0
I look up in this forum and found anything about this.
Unfortunately when you pipe to a while read loop it is executed in a subshell.
Try doing this instead:
while read var; do
echo $count
count=$((count+1))
done < file.tx
Annihilannic,
Thank a lot.
Trouble solved.
I am not using a pipe , but getting the same problem(sample shell script below,tree1.txt has 3 lines) , Any help would be highly appreciated:
count=0
export count
while read line
do
count=10
echo $count
done < tree1.lst
echo count:$count
Result:
10
10
10
count:0
How are you running the script? Which SHELL are you using? Ideally the above script should give you the same o/p. ie. 10.