[NTLUG:Discuss] bash question...beating a dead horse...
kbrannen@gte.net
kbrannen at gte.net
Tue Mar 5 21:45:01 CST 2002
Fred James wrote:
...
>
> 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?):
Yes.
> (1) How could I get the value of the counter for use after the second
> loop competes?
Count=0
while read animal color
do
echo "Inside second loop: animal:$animal color:$color $Count"
Count=`expr $Count + 1`
done < fun.txt
# ^^^^^^^^^
echo "Outside second loop animal:$animal color:$color $Count"
> (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?
I don't think so, for the same reason you're having to begin with.
Normally, you'd want to return the "values you're read", and capture those
into a variable. The simple example is:
x=`wc fun.txt` # note, those are back-ticks around the command
echo $x # gives " 4 4 19 fun.txt"
There's probably a way to do what you want in a generic fashion, but I don't
know of one.
Do you have to use bash? Perl would handle this easily. (if you know Perl :-)
Kevin
>
> Thanks in advance for your thoughts and efforts.
>
>
> Script file:
> ==========
> #! /bin/bash
> # count.sh
>
...
>
> Count=0
> cat fun.txt | while read animal color
> do
> echo "Inside second loop: animal:$animal color:$color $Count"
> Count=`expr $Count + 1`
> done
> echo "Outside second loop animal:$animal color:$color $Count"
...
More information about the Discuss
mailing list