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 ?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With