Loop over tuples in bash? Loop over tuples in bash? bash bash

Loop over tuples in bash?


$ for i in c,3 e,5; do IFS=","; set -- $i; echo $1 and $2; donec and 3e and 5

About this use of set (from man builtins):

Any arguments remaining after option processing are treated as values for the positional parameters and are assigned, in order, to $1, $2, ... $n

The IFS="," sets the field separator so every $i gets segmented into $1 and $2 correctly.

Via this blog.

Edit: more correct version, as suggested by @SLACEDIAMOND:

$ OLDIFS=$IFS; IFS=','; for i in c,3 e,5; do set -- $i; echo $1 and $2; done; IFS=$OLDIFSc and 3e and 5


This bash style guide illustrates how read can be used to split strings at a delimiter and assign them to individual variables. So using that technique you can parse the string and assign the variables with a one liner like the one in the loop below:

for i in c,3 e,5; do     IFS=',' read item1 item2 <<< "${i}"    echo "${item1}" and "${item2}"done


Based on the answer given by @eduardo-ivanec without setting/resetting the IFS, one could simply do:

for i in "c 3" "e 5"do    set -- $i    echo $1 and $2done

The output:

c and 3e and 5