Loop over tuples in bash?

后端 未结 12 1504
说谎
说谎 2020-12-04 21:00

Is it possible to loop over tuples in bash?

As an example, it would be great if the following worked:

for (i,j) in ((c,3), (e,5)); do echo \"$i and $         


        
12条回答
  •  春和景丽
    2020-12-04 21:05

    Using printf in a process substitution:

    while read -r k v; do
        echo "Key $k has value: $v"
    done < <(printf '%s\n' 'key1 val1' 'key2 val2' 'key3 val3')
    

    Key key1 has value: val1
    Key key2 has value: val2
    Key key3 has value: val3
    

    Above requires bash. If bash is not being used then use simple pipeline:

    printf '%s\n' 'key1 val1' 'key2 val2' 'key3 val3' |
    while read -r k v; do echo "Key $k has value: $v"; done
    

提交回复
热议问题