0

I know I can iterate over a list in bash like so:

for reg in xmm ymm zmm; do
  echo "Reg is $reg"
done

Great.

What if I want to iterate over a list of tuples, like (fake syntax):

for reg, size in (xmm, 128) (ymm, 256) (zmm, 512); do
  echo "Reg $reg has size $size"
done

It should print out:

Reg xmm has size 128
Reg ymm has size 256
Reg ymm has size 512

What is a convenient way to do this?

BeeOnRope
  • 60,350
  • 16
  • 207
  • 386

2 Answers2

2

You'll have to iterate over strings that you can split using read. For example:

while IFS=, read -r reg size; do
    echo "Reg $reg has size $size"
done <<EOF
xmm,128
ymm,256
zmm,521
EOF

or

for x in xmm,128 ymm,256 zmm,512; do
    IFS=, read reg size <<< "$x"
    echo "Reg $reg has size $size"
done
chepner
  • 497,756
  • 71
  • 530
  • 681
1

You can use printf in process substitution and read it in 2 variable in a while loop like this:

while read -r reg size; do
    echo "Reg $reg has size $size"
done < <(printf '%s %s\n' xmm 128 ymm 256 zmm 512)

Reg xmm has size 128
Reg ymm has size 256
Reg zmm has size 512

You may also use this alternate printf command:

printf '%s\n' 'xmm 128' 'ymm 256' 'zmm 512'
anubhava
  • 761,203
  • 64
  • 569
  • 643