chiru chiru - 4 months ago 7
Bash Question

Reading multiple parameters in for loop in shell

I want to read partition and replicationfactor as parameter in my for loop how can i do that? Instead of 2 and 3 i want to read from rf and partition the corresponding values for raw good and bad.

topics=(raw good bad)
rf=(4 6 8)
partition=(2 3 4)
for topic in ${topics[*]}
do
bin/kafka-topics.sh --create --replication-factor 2 --partitions 3 --topic "$topic" --zookeeper $zk_hosts
done

Answer

Sounds like you need a numeric loop:

for (( i = 0; i < ${#topics[@]}; ++i )); do
    # whatever you want with the corresponding elements of each array, e.g. 
    echo "${topics[i]} ${rf[i]} ${partition[i]}"
done

The loop counter goes from 0 to the length of the array topics, so this assumes that each of the other arrays has the same number of elements.