Results 1 to 3 of 3
This really has me stumped: First script gives the expected output, however when I change the nested loop from a "for" loop to a "while" loop, observe what happens to ...
- 03-04-2010 #1Just Joined!
- Join Date
- Jan 2007
- Posts
- 19
while loop read mystery
This really has me stumped: First script gives the expected output, however when I change the nested loop from a "for" loop to a "while" loop, observe what happens to the count output:
#!/bin/bash
count=1
for line in one two threeXfour fiveXsix seven eight
do
echo "$line" | grep "X" > /dev/null
if [ $? == 0 ]
then
var=`echo "$line" | sed 's/X/\n/g'`
for line2 in $var
do
echo $count
let count=count+1
echo $line2
done
else
echo $count
let count=count+1
echo $line
fi
done
#output:
1
one
2
two
3
three
4
four
5
five
6
six
7
seven
8
eight
When reading from a "while" loop, output is as follows:
#!/bin/bash
count=1
for line in one two threeXfour fiveXsix seven eight
do
echo "$line" | grep "X" > /dev/null
if [ $? == 0 ]
then
echo "$line" | sed 's/X/\n/g' | \
while read line2
do
echo $count" " > /dev/stderr
let count=count+1
echo $line2
done
else
echo $count" " > /dev/stderr
let count=count+1
echo $line
fi
done
#output
1
one
2
two
3
three
4
four
3
five
4
six
3
seven
4
eight
Anyone know why?
- 03-04-2010 #2Linux User
- Join Date
- Nov 2009
- Location
- France
- Posts
- 292
Piping to a while loop makes the loop to run in a sub-shell. There was a discussion about it on this forum recently, I can't trace it back. You can get more info here :
Variable Scope in Bash (NuclearDonkey.net)0 + 1 = 1 != 2 <> 3 != 4 ...
Until the camel can pass though the eye of the needle.
- 03-04-2010 #3Just Joined!
- Join Date
- Jan 2007
- Posts
- 19
aaahhh, thanks.


Reply With Quote