3

I have two separate lists. One contains 1000 hostnames and other contains 1000 associated IP's for that hosts. I need to generate config entries and push to my config file to add all hosts under our monitoring environment.

    #!/bin/bash
    Enter the hostnames
    readarray hosts
    Enter the IP's
    readarray IP

How should I iterate one by one in a loop like below? I know how to iterate single array by using for i in "${hosts[@]}", but in the case of two separate lists, how to achieve iteration?

    echo -e "\nObject host \""$hosts"\"{"
    import = \""generic-service"\"
    address = \""$IP"\"
    group = \""Mom1-Ping"\" 
    "\n}" >> /etc/icinga2/zones.d/mom2/AP.conf

Example of first list (List 1):

sjc02-mfg-api01.example.com 
sjc02-mfg-api02.example.com
sjc02-mfg-api03.example.com

upto 1000 hosts

Example of second list (List 2):

10.20.2.22 
10.20.2.23 
10.20.2.24

up to to 1000 IP's

Expected output:

     Object host "sjc02-mfg-api01.example.com" {
     import = "generic-service"
     address = "10.20.2.22"
     group = "Mom01-Ping"
     }

     Object host "sjc02-mfg-api02.example.com" {
     import = "generic-service"
     address = "10.20.2.23"
     group = "Mom01-Ping"
     }

     Object host "sjc02-mfg-api03.example.com" {
     import = "generic-service"
     address = "10.20.2.24"
     group = "Mom01-Ping"
     }

     ..........like this I need to generate to all 1000 hosts.............
5

Combine your both lists together using paste. You can do it as follows:

#!/bin/bash
paste list1 list2 | while IFS=$'\t' read -r L1 L2    
do
echo "
Object host ${L1} {
     import = "generic-service"
     address = ${L2}
     group = "Mom01-Ping"
     }"   
done 

output:

Object host sjc02-mfg-api01.example.com  {
     import = generic-service
     address = 10.20.2.22 
     group = Mom01-Ping
     }

Object host sjc02-mfg-api02.example.com {
     import = generic-service
     address = 10.20.2.23 
     group = Mom01-Ping
     }

Object host sjc02-mfg-api03.example.com {
     import = generic-service
     address = 10.20.2.24
     group = Mom01-Ping
     }
2

You can iterate over the indices of the pair of arrays:

a1=(foo bar baz)
a2=(one two three)

for ((i=0; i < "${#a1[@]}"; i++)); do 
    echo "${a1[i]} => ${a2[i]}"
done

where ${#a1[@]} is the size of the a1 array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.