Using “while read…” in a Linux Script – Bash Scripting Guide


Could somebody please explain how the following code works?

echo '1 2 3 4 5 6' | while read a b c
  echo $c $b $a

Specifically, I'd like to know why the output of this loop is 3 4 5 6 2 1, instead of 3 2 1 and 6 5 4 on two separate lines? I can't seem to wrap my mind around it…

Best Answer

read reads a whole line from standard input, splits the line into fields and assigns this fields to the given variables. If there are more pieces than variables, the remaining pieces are assigned to the last variable.

In your case $a is assigned 1, $b is assigned 2 and $c the remaining 3 4 5 6.

Related Question