nerdexam
CompTIA

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.

Shells, Scripting and Data Management

Question

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

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)
  • A
    55% (16)
  • B
    3% (1)
  • C
    7% (2)
  • D
    14% (4)
  • E
    21% (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.

Aresult: 3 4 5 6 2 1Correct

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.

Bresult: 1 2 3 4 5 6

This would be the output if echo result: $a $b $c was used, or if read assigned all words to a single variable.

Cresult: 6 5 4

This output incorrectly truncates the input and also incorrectly reverses the segments.

Dresult: 6 5 4 3 2 1

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.

Eresult: 3 2 1

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

#shell scripting#pipelines#read command#while loops

Community Discussion

No community discussion yet for this question.

Full LX0-104 Practice