2

Here is the script:

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

The result is 3 4 5 6 2 1 Can someone explain why?

5

The final data on the line will be put in the last variable, i.e. c contains "3 4 5 6". So you probably want:

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

and ignore variable rest.

6

read breaks up each line of standard input into words the same way that your shell does when you write commands. After that:

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

In your case, a is assigned the value 1, b is assigned the value 2, and c gets the rest of the line "3 4 5 6". You print out c (3 4 5 6), then b (2), then a (1), giving you output you see.

The loop isn't doing anything in this case, since there's only a single line to read from your first echo.

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.