Reputation: 2639
I observe a behavior that I don't undrestand and would like someone to shed some light on it.
I have two scripts, both read from STDIN.
Reading a sequence of numbers from keyboard ( 1 enter 2 enter 3 enter ... )
Script A prints "x" everytime
#!/bin/bash
while read LINE
do
echo "x" # this happens everytime
echo $LINE # this is the only different line
done
output:
1
x
1
2
x
2
3
x
3
4
x
4
5
x
5
Script B prints "x" only the first time it reads LINE
#!/bin/bash
while read LINE
do
echo "x" # this happens only the first time
awk '{print $LINE}' # this is the only different line
done
output:
1
x
2
2
3
3
4
4
5
5
Can someone explain this ?
Upvotes: 3
Views: 440
Reputation: 8839
awk took control of your stdin. If you type the following on command line, you will see what happens.
awk '{print $LINE}'
Your ctrl-D will finish the stdin to awk and take you back into the while loop.
Upvotes: 2
Reputation: 531125
The loop is still in its first iteration. awk
is reading all successive input, not the read
command. The awk
statement is also not printing the value of a shell variable LINE
, since it is not expanded inside the single quotes. Rather, awk
sees that its internal variable LINE
is undefined, and treats it as having the value 0. awk
then prints the value of $0
, which is the line that it reads from standard input.
Upvotes: 3