LFCS · 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 assigns words from its input to specified variables, with the last variable receiving all remaining input on the line.
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
(28 responses)- A82% (23)
- B4% (1)
- D4% (1)
- E11% (3)
Why each option
The `read` command assigns words from its input to specified variables, with the last variable receiving all remaining input on the line.
The `echo '1 2 3 4 5 6'` command pipes the string to the `while read a b c` loop. The `read` command assigns the first word ('1') to `a`, the second word ('2') to `b`, and all remaining words on the line ('3 4 5 6') to `c`. Consequently, `echo result: $c $b $a` outputs 'result: 3 4 5 6 2 1'.
This output would occur if `read` assigned the entire string to a single variable or if the variables were not reordered in the `echo` command.
This output is incorrect because variable `c` would contain '3 4 5 6', not just '3' or '4'.
This output implies a full reversal of the input words, which is not how `read` assigns multiple words to a limited number of variables.
This output is incorrect because `c` would contain '3 4 5 6', not just '3', and it misrepresents the full input assigned to variables.
Concept tested: Shell `read` command behavior with multiple variables
Source: https://man7.org/linux/man-pages/man1/bash.1.html
Topics
Community Discussion
No community discussion yet for this question.