我有两个单独的列表。其中一个包含 1000 个主机名,另一个包含该主机的 1000 个关联 IP。我需要生成配置条目并推送到我的配置文件以添加我们的监控环境下的所有主机。
#!/bin/bash
Enter the hostnames
readarray hosts
Enter the IP's
readarray IP
我应该如何在如下循环中一项一项地迭代?我知道如何使用 迭代单个数组for i in "${hosts[@]}"
,但是在两个单独的列表的情况下,如何实现迭代?
echo -e "\nObject host \""$hosts"\"{"
import = \""generic-service"\"
address = \""$IP"\"
group = \""Mom1-Ping"\"
"\n}" >> /etc/icinga2/zones.d/mom2/AP.conf
第一个列表的示例(列表 1):
sjc02-mfg-api01.example.com
sjc02-mfg-api02.example.com
sjc02-mfg-api03.example.com
最多 1000 个主机
第二个列表的示例(列表 2):
10.20.2.22
10.20.2.23
10.20.2.24
最多 1000 个 IP
预期输出:
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.............
答案1
使用 将两个列表合并在一起paste
。您可以按如下方式进行操作:
#!/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
输出:
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
您可以迭代指数数组对的:
a1=(foo bar baz)
a2=(one two three)
for ((i=0; i < "${#a1[@]}"; i++)); do
echo "${a1[i]} => ${a2[i]}"
done
哪儿${#a1[@]}
是尺寸a1 数组的