我有以下脚本:
#!/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我需要不断地点击这些地址,直到它们都成功,然后执行一个命令。我不需要成功/失败的输出,我只是想要平所有的IP,然后回应“所有主机在线”,例如。
发布于 2016-03-16 10:55:30
我希望代码中的注释能清楚地说明这是做什么的。基本上,诀窍是将整个事件封装在一个无限的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。
https://stackoverflow.com/questions/36033484
复制相似问题