Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: Odd behavior reading from STDIN in a loop

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 ?

like image 876
Tulains Córdova Avatar asked Sep 19 '26 12:09

Tulains Córdova


2 Answers

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.

like image 178
chepner Avatar answered Sep 22 '26 02:09

chepner


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.

like image 42
unxnut Avatar answered Sep 22 '26 01:09

unxnut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!