102-500 · Question #15
What output is produced by the following command sequence? echo `1 2 3 4 5 6' | while read a b c; do echo result $c $b $a; done
The correct answer is C. result: 3 4 5 6 2 1. Option C is correct because read a b c splits the input 1 2 3 4 5 6 by whitespace and assigns words left-to-right - but the last variable absorbs all remaining tokens: a=1, b=2, c="3 4 5 6". The echo result $c $b $a then prints those three variables in reversed order, yielding…
Question
Options
- Aresult: 6 5 4
- Bresult: 1 2 3 4 5 6
- Cresult: 3 4 5 6 2 1
- Dresult: 6 5 4 3 2 1
- Eresult: 3 2 1
How the community answered
(32 responses)- A3% (1)
- B9% (3)
- C78% (25)
- D3% (1)
- E6% (2)
Explanation
Option C is correct because read a b c splits the input 1 2 3 4 5 6 by whitespace and assigns words left-to-right - but the last variable absorbs all remaining tokens: a=1, b=2, c="3 4 5 6". The echo result $c $b $a then prints those three variables in reversed order, yielding result 3 4 5 6 2 1.
Why the distractors fail:
- E (
result 3 2 1) is the trap - it assumesc=3only, forgetting the last-variable-catches-all rule. - D (
result 6 5 4 3 2 1) would require the entire string to be fully reversed, whichreaddoesn't do. - A (
result 6 5 4) would require only the last three tokens assigned toc b a- the opposite assignment logic. - B (
result 1 2 3 4 5 6) would result if the variables were echoed in original order with no splitting.
Memory tip: When read has fewer variables than words, think of the last variable as a bucket - it catches everything the earlier variables didn't claim. Apply this before reversing the echo order.
Topics
Community Discussion
No community discussion yet for this question.