LX0-104 · Question #120
What output will the following command sequence produce? echo '1 2 3 4 5 6' | while read a b c; do echo result: $c $b $a; done
The correct answer is A. result: 3 4 5 6 2 1. The 'read' command in the 'while' loop assigns the first word to 'a', the second to 'b', and all remaining words from the input line to 'c', which are then echoed in reverse order.
Question
Options
- Aresult: 3 4 5 6 2 1
- Bresult: 1 2 3 4 5 6
- Cresult: 6 5 4
- Dresult: 6 5 4 3 2 1
- Eresult: 3 2 1
How the community answered
(29 responses)- A55% (16)
- B3% (1)
- C7% (2)
- D14% (4)
- E21% (6)
Why each option
The 'read' command in the 'while' loop assigns the first word to 'a', the second to 'b', and all remaining words from the input line to 'c', which are then echoed in reverse order.
The echo '1 2 3 4 5 6' command pipes the string '1 2 3 4 5 6' to the while read a b c loop. The read command assigns '1' to variable a, '2' to variable b, and then assigns all remaining words ('3 4 5 6') to variable c. The echo result: $c $b $a command then prints 'result: 3 4 5 6 2 1'. The loop executes only once as there is only one line of input.
This would be the output if echo result: $a $b $c was used, or if read assigned all words to a single variable.
This output incorrectly truncates the input and also incorrectly reverses the segments.
This implies that each word was read individually and then reversed, which is not how read with multiple variables behaves for a single line of input.
This output incorrectly truncates and reverses the segments.
Concept tested: Shell read command behavior with multiple variables
Source: https://www.gnu.org/software/bash/manual/bash.html#index-read
Topics
Community Discussion
No community discussion yet for this question.