An overdose of spam made Herve Couppe de Lahongrais - CDL
>> Hi,
>> After tearing my hair out for a while I found the cause of my problem,
>> but I don't really understand it and can't seem to find a way round it.
>> If I enter the following:
>> #!/bin/sh
>> i=0
>> while read line; do
>> i=`expr $i + 1`
>> echo "i is $i"
>> test $i -eq 10 && break
>> done < SomeFileWithMoreThan10Lines
>> echo "Finally i is $i"
>> Then after the while i is still 0, now I assume this has something to do
>> with the way 'read' works because a straight while(true) loop works
>> fine.
>This is because the while loop is redirected from
>SomeFileWithMoreThan10Lines.
>If redirection is used in a non-simple command (for, if, while, {},
>etc.)
>a subshell is created to execute that command. This implies that any
>shell
>variables set, created, or modified within the command do not retain
>their
>values after execution. If no redirection is used, a subshell is not
>created,
>and shell modifications made within the command are preserved.
>> I did try a variation on the 'read a line at a time' theme using:
>> for line in `cat file`;do
>> # process line
>> done
>> but the problem with this is that it splits lines by spaces and I get
>> fields in the line one at a time rather than the whole line.
>> Any help would be greatly appreciated.
>> Simon
>You can try :
>#!/bin/sh
>i=0
>{ while read line; do
> i=`expr $i + 1`
> echo "i is $i"
> test $i -eq 10 && exit $i
> done
> exit $i
>} < SomeFileWithMoreThan10Lines
>i=$?
>echo "Finally i is $i"
ksh seems to handle this in the required manner (tested on Solaris):
>cat looper.sh
#!/bin/ksh
i=0
while read line; do
i=`expr $i + 1`
echo "i is $i"
test $i -eq 10 && break
done < .profile
echo "Finally i is $i"
>looper.sh
i is 1
i is 2
i is 3
i is 4
i is 5
i is 6
i is 7
i is 8
i is 9
i is 10
Finally i is 10
>
you can escape doing the redirection on the loop in Bourne shell by using
exec, thus:
>cat looper2.sh
#!/bin/sh
exec 3<&0 0<.profile
i=0
while read line; do
i=`expr $i + 1`
echo "i is $i"
test $i -eq 10 && break
done
exec 0<&3 3<&-
echo "Finally i is $i"
>looper2.sh
i is 1
i is 2
i is 3
i is 4
i is 5
i is 6
i is 7
i is 8
i is 9
i is 10
Finally i is 10
>
cheers
andrew
--
-------------------------------------------------------------------------
There's nothing either good or bad, but thinking makes it so - Hamlet
http://www.gr-lakes.com/~andrew (including PGP key)
PGP Key fingerprint = 5C 44 7D E4 76 A3 31 DE 3D 11 FA 15 4D 87 1F 5E
-------------------------------------------------------------------------