Search code examples
bashloops

What is the equivalent of python zip() function in linux bash?


I would like to iterate over pairs of elements in bash. In Python, this is straigthforward:

x_list = [1, 2, 3, 4]
y_list = ["a", "b", "c", "d"]

for x, y in zip(x_list , y_list):
    # here we have access to the values (i.e. the pairs are assigned to variables):
    result = do_something(x, y)
    print(result)

How can I replicate such a behavior in bash? I would need to store the values of the pairs into variables inside of the for loop, so that I can perform some operations. It should be something like:

for x, y in 1a 2b 3c 4d
  do 
     python script.py --x_value=${x} --y_value=${y}
  done

Note that the elements of the list could be also complicated stuff, such as: x_list = [1e-5, 1e-4, 1e-3] and y_list = [10, 20, 30]


Solution

  • A possible translation of your code would be:

    #!/bin/bash
    
    x_list=(1 2 3 4)
    y_list=(a b c d)
    
    for i in "${!x_list[@]}"
    do
        x=${x_list[i]}
        y=${y_list[i]}
        printf '%q %q\n' "$x" "$y"
    done
    
    1 a
    2 b
    3 c
    4 d
    

    Just be aware that it relies of the fact that the two newly created arrays will have identical indexes. Here's an illustration of the problem:

    #!/bin/bash
    
    x_list=(1 2 3 4)
    y_list=(a b c d)
    
    unset y_list[1]
    
    for i in "${!x_list[@]}"
    do
        x=${x_list[i]}
        y=${y_list[i]}
        printf '%q %q\n' "$x" "$y"
    done
    
    1 a
    2 ''
    3 c
    4 d