Quote:
Originally Posted by Darren[UoW]
I am using the following code to read line by line from a file, however my problem is that $value=0 at the end of the loop possibly because bash has created a subshell for the loop or something similar. How can I solve this.
value=0;
while read line
do
value=`expr $value + 1`;
echo $value;
done < "myfile"
echo $value;
Note: This example just counts the number of lines, I actually desire to do more complex processing than this though, so 'wc' is not an alternative, nor is perl im afraid.
Thanks Darren.
|
Indeed a while loop is a block, that
can be executed in a sub shell.
A sub shell is a fork of the main shell, so it inherits the variables, but there is no easy way to copy its variables back to the main shell.
It depends on the implementation:
Traditional Unix shells make it a sub shell when the block's input/output is redirected or piped.
Your work-around then is:
Code:
value=0
#save &0 in the unused &5
exec 5<&0
# read &0 from file
exec <"myfile"
while read line
do
value=...
...
done
#restore &0
exec <&5
echo $value
Posix shells, ksh, bash, zsh only make a sub shell when the block's input/output is piped (and they support the built-in $((numeric expression)).Darren's code works.
Ksh and zsh handle the last part of a pipe in the main shell, so even this one works:
Code:
value=0
cat "myfile" | while read line
do
value=...
...
done
echo $value