[NTLUG:Discuss] bash question...beating a dead horse...
Chris Cox
cjcox at acm.org
Tue Mar 5 22:12:46 CST 2002
Fred James wrote:
>
> My questions revolve around the shell script, and text, files below - I
> know I have already received some good answers on this but I guess I am
> just slow or something.
>
> The script contains 3 loops, each of which increment a counter that has
> been initialized to zero. When I run this on my Red Hat 7.1 laptop:
> (1) the count is 10 outside (after) the first loop
> (2) the count is zero outside (after) the second loop.
> (3) the count is 4 outside (after) the third loop.
>
> So, if the counter in the second loop is lost outside that loop because
> the loop is executed in a subscript (is that the explanation?):
> (1) How could I get the value of the counter for use after the second
> loop competes?
> (2) If I assigned the values read into an array, would the contents of
> the array be available after the loop completes - if not normally, is
> there a way to do so?
>
> Thanks in advance for your thoughts and efforts.
>
Modified script follows... see comments in script (this is one way to do this):
#! /bin/bash
#
#count.sh
Count=0
while test $Count -lt 10
do
echo "Inside first loop $Count" >&2
Count=`expr $Count + 1`
done
echo "Outside first loop $Count"
#Count=0
#
# Because of the redirection, this loop will execute within
# a subshell in bash. I created yet another subshell so
# we could incapsulate the return value to pass back on
# end of loop.
#
# The return values will come to standard out in the form of
# a shell string of assignments that can be eval'd afterwards.
# Therefore, the output from the echo we need to send somewhere
# else... like stderr (file descriptor 2).
#
# Other issues are that the loop will end on eof on the read
# and the last values for animal, etc, will be empty on
# loop termination.... perhaps that is what you expected...
# ...anyway, I went ahead and preserved the last real values
# into some temporary variables for use afterwards.
#
# Same with subsequent loop.. the first one just invokes the
# extraneous cat process.
#
rc=`cat fun.txt | (Count=0;while read animal color
do
echo "Inside second loop: animal:\$animal color:\$color \$Count" >&2
Count=\`expr \\$Count + 1\`
lanimal=\$animal;lcolor=\$color
done;echo "animal='\$lanimal';color='\$lcolor';Count='\$Count';")`
#
# Beware, the eval here assumes you know your data is safe from
# side effects due to the eval.
#
eval $rc
echo "Outside second loop animal:$animal color:$color $Count"
#Count=0
rc=`(Count=0;while read animal color
do
echo "Inside third loop: animal:\$animal color:\$color \$Count" >&2
Count=\`expr \\$Count + 1\`
lanimal=\$animal;lcolor=\$color
done;echo "animal='\$lanimal';color='\$lcolor';Count='\$Count';") <fun.txt`
eval $rc
echo "Outside third loop animal:$animal color:$color $Count"
exit
More information about the Discuss
mailing list