Reading multiple values in while loop

I'm having trouble with a simple piece of code.

IFS=,
echo "1,2,3,4,5,6,7,8" | while read x y
do
echo "x=$x"
echo "y=$y"
done
 

I'm hoping for
x=1
y=2
x=3
y=4
.
.
.

but I'm getting
x=1
y=2,3,4,5,6,7,8

what am I missing here?

Hi, execute this

IFS=,
echo "1,2
3,4
5,6
7,8" | while read x y
do
echo "x=$x"
echo "y=$y"
done
1 Like

read is a line reading tool and the last value read in one iteration of the command is treated as the remainder of the line even if contains field separators. Fortunately you can change the line delimiter with the -d option:

IFS=,
echo "1,2:3,4:5,6:7,8" | while read -r -d ':' x y
do
echo "x=$x"
echo "y=$y"
done

Mike

PS. read is capable of escaping characters and you can turn this off with -r. As a general rule, you should always use -r unless you have a reason not to.

2 Likes

Thanks to both for the quick reply.

Newline in the input wasn't an option with my real life data, but Michael Stora's suggestion solved my problem.