LFCS · Question #547
Which of the following outputs will the below 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 echo command pipes a single line of space-separated numbers to a while read loop, which assigns the first two words to a and b, and all remaining words to c, then echoes them 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
(40 responses)- A80% (32)
- B13% (5)
- D5% (2)
- E3% (1)
Why each option
The `echo` command pipes a single line of space-separated numbers to a `while read` loop, which assigns the first two words to `a` and `b`, and all remaining words to `c`, then echoes them in reverse order.
The `read` command, when given multiple variable names, assigns the first word to `a` ('1'), the second word to `b` ('2'), and then assigns all remaining words on the line ('3 4 5 6') to the last variable `c`. The `echo` command then prints these variables in the order `$c $b $a`.
This output implies the variables were not assigned correctly or were echoed in their original order.
This output only shows the last three numbers, indicating an incorrect understanding of how `read` handles multiple words with multiple variables.
This output implies a complete reversal of all numbers, which would only happen if each number was read into a separate variable and then processed.
This output implies only the first three numbers were processed and reversed, but `read` assigns all remaining words to the last variable.
Concept tested: Bash `read` command behavior
Source: https://www.gnu.org/software/bash/manual/bash.html#index-read
Topics
Community Discussion
No community discussion yet for this question.