Loop over tuples in bash?

后端 未结 12 1518
说谎
说谎 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:20

    c=('a' 'c')
    n=(3    4 )
    
    for i in $(seq 0 $((${#c[*]}-1)))
    do
        echo ${c[i]} ${n[i]}
    done
    

    Might sometimes be more handy.

    To explain the ugly part, as noted in the comments:

    seq 0 2 produces the sequence of numbers 0 1 2. $(cmd) is command substitution, so for this example the output of seq 0 2, which is the number sequence. But what is the upper bound, the $((${#c[*]}-1))?

    $((somthing)) is arithmetic expansion, so $((3+4)) is 7 etc. Our Expression is ${#c[*]}-1, so something - 1. Pretty simple, if we know what ${#c[*]} is.

    c is an array, c[*] is just the whole array, ${#c[*]} is the size of the array which is 2 in our case. Now we roll everything back: for i in $(seq 0 $((${#c[*]}-1))) is for i in $(seq 0 $((2-1))) is for i in $(seq 0 1) is for i in 0 1. Because the last element in the array has an index which is the length of the Array - 1.

提交回复
热议问题