Why the following does not print 3 2 1 6 5 4?

echo '1 2 3 4 5 6' | while read a b c; do echo result: $c b a; done

Wouldn't the first three numbers be read in order, printed in reverse, and then the last three numbers read and reversed?


You provided a line with 6 "words", yet you're reading them into three variables: a, b, and c. The first variable a is assigned 1, the second variable b is assigned 2, and c gets to hold the rest of the line: "3 4 5 6".

The output is 3 4 5 6 b a because you didn't write $c $b $a, but only $c b a.

If you had written $c $b $a, the result would have been 3 4 5 6 2 1.


The key point that is confusing you, which the other answer skims over, can be seen in the bash man page:

read …(options)… [name ...]

    One line is read from the standard input, …, and the first word is assigned to the first name, the second word to the second name, and so on, with leftover words and their intervening separators assigned to the last name.  …         [Emphasis added.]

or in the output of help read:

read …(options)… [name ...]

    Read a line from the standard input and split it into fields.

    Reads a single line from the standard input, ….  The line is split into fields as with word splitting, and the first word is assigned to the first NAME, the second word to the second NAME, and so on, with any leftover words assigned to the last NAME.  …

The point: read never reads more than one line.

  • Actually, the point that is confusing the OP is that read reads a whole line. Here there's a single line of input, but the OP expected the loop body to run twice. Apr 24 '16 at 20:08
  • Ah, true; read never reads less than one line (although that's not exactly true, either).  I always get those concepts mixed up.    :-)    ⁠ Apr 24 '16 at 21:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.