Sonique
Sonique

Reputation: 7110

bash script - iterate over two (or more) ranges simultaneously in for loop

I know that is possible to iterate over few arrays in bash for loop or any command like echo (Brace Expansion).

for i in {1..4} {a..d}
    echo $i

# or
echo {1..4} {a..d}

# output: 1 2 3 4 a b c d

But is it possible to iterate over arrays simultaneously to get result like:

# output: 1 a 2 b 3 c 4 d

For example I need to ssh to three range of servers with names like server-a1.com, server-b1.com, server-c1.com and need to perform action on all firsts, than on all seconds and so on.

Upvotes: 1

Views: 1020

Answers (4)

user2350426
user2350426

Reputation:

#!/bin/bash
a=({1..4})    b=({a..d})    i=0                ### Initial values

for ((i=0; i<4; i++ )) ; do                    ### Loop over elements
      printf '%s %s    ' "${a[i]}" "${b[i]}"   ### Print pairs of values.
done
echo

$ ./script.sh
1 a    2 b    3 c    4 d

Upvotes: 1

joepd
joepd

Reputation: 4841

This will do what you want:

a=( {1..4} )
b=( {a..d} )
for (( i=0; i<${#a[@]}; i++ )); do
    echo -n "${a[i]} ${b[i]} "
done

The range expansion is put into two arrays. The index of the first array are used to refer to both arrays.

Upvotes: 1

choroba
choroba

Reputation: 241938

You can generate all the combinations with

echo {1..4}{a..d}

If you select each fifth, you'll get what you wanted:

all=({1..4}{a..d})
for (( i=0 ; i<${#all[@]} ; i++ )) ; do
    (( !(i % 5) )) && echo ${all[i]}
done

Upvotes: 2

shellter
shellter

Reputation: 37298

sure

 for i in {1..4} ; do
    for j in {a..d} ; do
       echo ssh  user@server-${i}${j}.com 'cmd'
    done
 done

output

ssh [email protected] cmd
ssh [email protected] cmd
ssh [email protected] cmd
ssh [email protected] cmd
ssh [email protected] cmd
ssh [email protected] cmd
ssh [email protected] cmd
. . .

Of course, you get to make your own ssh cmdline using the ${i} and ${j} when needed.

I have used echo ssh ... to be a placeholder for your real processes.

IHTH

Upvotes: 1

Related Questions