bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: while read subcommand problem


From: Kevin F. Quinn
Subject: Re: while read subcommand problem
Date: Fri, 2 Mar 2007 18:59:54 +0100

On Fri, 2 Mar 2007 03:04:14 -0800 (PST)
rleeden <rleeden@blueyonder.co.uk> wrote:

> 
> Hi,
> 
> I struggled recently with a 'while read' type of loop in bash, where
> after the loop had finished the variables used inside the loop are
> not visible any more. I soon found the problem as explained in
> section E4 of the FAQ. But I didn't find any of the alternate
> examples given very useful for what I want to do.
> 
> Let me give you a simplified example of something I'm attempting to
> do:
> 
> ---------------------------------------------------------
> #!/bin/bash
> 
> grep -v "^#" /etc/hosts | head -5 | while read IP HOSTNAME
> do
>         (( i++ ))
>         echo "$i : $IP $HOSTNAME"
> done
> 
> echo
> echo "Total : $i"
> 
> ---------------------------------------------------------
> 
> but the $i in the last line is empty - not set to 5 as it should be.
> 
> As you probably know, this kind of loop works fine in ksh.
> 
> NOTE: This is just an example, so I don't need alternatives for how I
> could achieve the specifics shown above. I need to find a good
> solution where I can do things with a file (whether it be with sed,
> awk, tail, head etc.) then pipe it into a 'while read' loop, and then
> after the loop access any variables set within the while loop. 
> 
> One alternative is to use a temporary file, but I would prefer not to
> - e.g.
> 
> ---------------------------------------------------------
> #!/bin/bash
> 
> grep -v "^#" /etc/hosts | head -5  > tmpfile
> 
> while read IP HOSTNAME
> do
>         (( i++ ))
>         echo "$i : $IP $HOSTNAME"
> done < tmpfile
> 
> rm tmpfile
> 
> echo
> echo "Total : $i"
> 
> ---------------------------------------------------------
> 
> 
> Any ideas?


You could use a here doc:

---------------------------------------------------------
#!/bin/bash

while read IP HOSTNAME
do
        (( i++ ))
        echo "$i : $IP $HOSTNAME"
done <<EOF
$(grep -v "^#" /etc/hosts | head -5)
EOF

echo
echo "Total : $i"
---------------------------------------------------------


-- 
Kevin F. Quinn

Attachment: signature.asc
Description: PGP signature


reply via email to

[Prev in Thread] Current Thread [Next in Thread]