尝试 ping IP 并返回带有 HOSTNAME 的结果。第一个 ip 有响应,第二个没有,但脚本打印所有 HOSTNAMES 如何将 IP (i) 与 HOSTNAME (h) 匹配?尝试过:
for i in 10.10.63.84 10.10.100.49; do for h in TEST NOCON
do
#Pinging IPs and report if success
ping -c 1 $i &> /dev/null;
if [ $? -eq 0 ]; then
echo "$h is alive"
else
echo "Please reboot $h!"
fi
done
done
result:
TEST is alive
NOCON is alive
Please reboot TEST!
Please reboot NOCON!
Should be
TEST is alive
Please reboot NOCON!
谢谢
答案1
嵌套的 for 循环意味着您正在处理交叉积:
10.10.63.84 TEST
10.10.63.84 NOCON
10.10.100.49 TEST
10.10.100.49 NOCON
您实际上想要 1:1 映射。为此使用关联数组:
declare -A hosts=(
[10.10.63.84]="TEST"
[10.10.100.49]="NOCON"
)
# iterate over the array _keys_
for ip in "${!hosts[@]}"; do
if ping -c 1 "$ip" &> /dev/null; then
echo "${hosts[$ip]} is alive"
else
echo "Please reboot ${hosts[$ip]}!"
fi
done