Ping 服务器并在所有响应时执行命令
Ping servers and execute command when all respond
我有以下脚本:
#!/bin/bash
servers=( "10.10.10.1" "10.10.10.2" "10.10.10.3" "10.10.10.4" )
for i in "${servers[@]}";
do
ping -c 4 "$i" >/dev/null 2>&1 &&
echo "Ping Status of $i : Success" ||
echo "Ping Status of $i : Failed"
done
输出
Ping Status of 10.10.10.1 : Success
Ping Status of 10.10.10.2 : Success
Ping Status of 10.10.10.3 : Failed
Ping Status of 10.10.10.4 : Failed
我需要不断地 ping 这些地址,直到它们都成功,然后执行命令。我不需要 success/failed 输出,我只想 ping 所有 IP,然后回显 "All Hosts Online",例如。
我希望代码中的注释能够清楚地说明这是做什么的。基本上,诀窍是将整个事情包装在一个无限 while
循环中,并使用一个变量来表示其中一个命令是否失败。
#!/bin/bash
servers=( "10.10.10.1" "10.10.10.2" "10.10.10.3" "10.10.10.4" )
# Keep looping forever : is a special builtin command that does
# nothing and always exits with code 0
while :; do
# Assume success
failed=0
# Loop over all the servers
for i in "${servers[@]}"; do
# We failed one!
if ! ping -c 4 "$i" >/dev/null 2>&1; then
# Set failed to 1 to signal the code after the for loop that
# a ping failed
failed=1
# We don't need to ping the others, so we can break from this for
# loop
break
fi
done
# If none of the ping commands failed, the $failed variable is still 0
if [ $failed -eq 0 ]; then
# Yes! We can now run our command
echo "All hosts online"
# And break the infinite while loop
break
else
# Nope, wait a while and start the loop from the top
sleep 5
fi
done
我也修正了一个错字;你用了 /dev/nul
,但应该是 /dev/null
,有两个 l
.
我有以下脚本:
#!/bin/bash
servers=( "10.10.10.1" "10.10.10.2" "10.10.10.3" "10.10.10.4" )
for i in "${servers[@]}";
do
ping -c 4 "$i" >/dev/null 2>&1 &&
echo "Ping Status of $i : Success" ||
echo "Ping Status of $i : Failed"
done
输出
Ping Status of 10.10.10.1 : Success
Ping Status of 10.10.10.2 : Success
Ping Status of 10.10.10.3 : Failed
Ping Status of 10.10.10.4 : Failed
我需要不断地 ping 这些地址,直到它们都成功,然后执行命令。我不需要 success/failed 输出,我只想 ping 所有 IP,然后回显 "All Hosts Online",例如。
我希望代码中的注释能够清楚地说明这是做什么的。基本上,诀窍是将整个事情包装在一个无限 while
循环中,并使用一个变量来表示其中一个命令是否失败。
#!/bin/bash
servers=( "10.10.10.1" "10.10.10.2" "10.10.10.3" "10.10.10.4" )
# Keep looping forever : is a special builtin command that does
# nothing and always exits with code 0
while :; do
# Assume success
failed=0
# Loop over all the servers
for i in "${servers[@]}"; do
# We failed one!
if ! ping -c 4 "$i" >/dev/null 2>&1; then
# Set failed to 1 to signal the code after the for loop that
# a ping failed
failed=1
# We don't need to ping the others, so we can break from this for
# loop
break
fi
done
# If none of the ping commands failed, the $failed variable is still 0
if [ $failed -eq 0 ]; then
# Yes! We can now run our command
echo "All hosts online"
# And break the infinite while loop
break
else
# Nope, wait a while and start the loop from the top
sleep 5
fi
done
我也修正了一个错字;你用了 /dev/nul
,但应该是 /dev/null
,有两个 l
.