bug-bash
[Top][All Lists]
Advanced

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

while read subcommand problem


From: rleeden
Subject: while read subcommand problem
Date: Fri, 2 Mar 2007 03:04:14 -0800 (PST)

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?


-- 
View this message in context: 
http://www.nabble.com/while-read-subcommand-problem-tf3332952.html#a9267658
Sent from the Gnu - Bash mailing list archive at Nabble.com.





reply via email to

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