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?
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.Sign up to join this community
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:
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
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. …
read never reads more than one line.