3

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 ?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Great answer, I swear I found this tricky situation by accident. It would make a good examination question for beginners, ha ha.
2

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.

1 Comment

Great answer, I swear I found this tricky situation by accident. It would make a good examination question for beginners, ha ha.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.