Ubuntu – For loop syntax bash script

bashscripts

Is there a way we can implement some thing like this in bash script ?

pureips="10.3.1.111 10.3.1.112 10.3.1.114";
pureservers="a b c";
for ip,server in $pureips,$pureservers; do
    echo "$server | $ip ";
done

Thanks.

Best Answer

If you want this to nest so each server runs against each IP (i.e. run 9 times) you can:

for ip in $pureips; do
    for server in $pureservers; do
        echo "$server | $ip "
    done
done

If you want to just track each item (eg run 3 times, running the first ip with the first server, the second with the second, etc) you can use an iterator and call the index of the array manually. But that does mean we'll also need to convert the strings into arrays first:

read -a pureips <<< "10.3.1.111 10.3.1.112 10.3.1.114"
read -a pureservers <<< "a b c"

for ((i=0; i<=${#pureips[@]}; i++)); do
    echo "${pureservers[i]} | ${pureips[i]}"
done
Related Question