while read in bash

Rusty Carruth plug-devel@lists.PLUG.phoenix.az.us
Mon May 28 21:26:01 2001


> 
> moin, moin,
> 
> I'm trying to loop over some input, toss some info in a variable, then
> access that info after the while loop is finished. Unfortunately, this isn't
> working. A while loop by itself will work fine, but with read it doesn't.
> 
> Here's an example script. Note that preassignment of the sought after
> variable doesn't affect the while read, but it does affect the condition
> clause of the while loop.
> 
> Anyone know how to make the info available beyond the done? Putting it in a
> function did not help. Reading from keyboard and not a pipe, however, does
> obtain the behavior I'm expecting.
> 
> --- cut here ---
> 
> liases2root="fred "
> count=0
> 
> # while read nickname destination otherdests
> grep root /etc/aliases | while read nickname destination otherdests

Well, what you expect the above to do is not at all what I'd have expected 
it to do..

Here's how I'd probably do it (I won't say do it in perl - even though
I've started to become much more of a 'do it in perl' person ;-)
the following lines replace the 'grep root ...' and the 'do' lines -
not really pretty, but it SHOULD work...)  (its tired, and I'm late ;-)

grep root /etc/aliases > /tmp/$$.roots
nlines=`wc -l /tmp/$$.roots`
i=0
while [ $i -lt $nlines ] ; do

Oh, shoot, this is getting way to complex.  DO it in awk:

grep root /etc/aliases | awk  '/root/ { print $1 } {next;}'

Then just make it prettier as you need... (for example:

grep root /etc/aliases | awk  -F: '/root/ { printf("%s ",$1)} {next;}'

That still needs a little work, in case there are any comments...

Anyway, there ya go...

> do
>         if [ "$destination" = "root" ] ; then
>                 # echo $nickname
>                 aliases2root="$aliases2root $nickname"
>                 echo $aliases2root
>         fi      
> done    
> 
> while [ $count -lt 5 ]
> do
>         count=`expr $count + 1`
> done
> 
> echo "<$aliases2root> <$count>"
> --- cut here ---
> 
> ciao,
> 
> der.hans
> -- 
> # der.hans@LuftHans.com home.pages.de/~lufthans/ www.DevelopOnline.com
> #  Help Jerry Lewis stamp out M$...oops that's MDA - der.hans
> 
> _______________________________________________
> PLUG-devel mailing list  -  PLUG-devel@lists.PLUG.phoenix.az.us
> http://lists.PLUG.phoenix.az.us/mailman/listinfo/plug-devel
>