一个接一个地 ping 一台设备并检查可用性
ping one device after the other and check availability
我想在我的 raspi 上 运行 一个 bash 脚本。
该脚本的目的是检查我网络中的一台设备的可用性(使用 ping)。
如果此设备正在响应,脚本应该结束。
如果它没有响应,它必须进一步检查 3 个特定设备的可用性:如果这 3 个设备中的一个正在响应,则发送邮件;如果这些设备中的 none 有响应,则什么都不做。
我希望我到目前为止所做的是可识别的:
#!/bin/bash
array=(192.168.xxx.xxx 192.168.xxx.xxx)
ping -c 1 192.168.xxx.xxx
if [$? -eq 0]; then exit 0
else
for devices in "${array[@]}"
do ping -c 1 $devices &> /dev/null
if [ $? -eq 0 ]; then exit 0
fi
fi
done
/usr/sbin/sendmail foo@bar.com < /home/pi/scripts/email.txt
我现在很卡,因为我的脚本技术差得吓人。
您的代码中有两个错误:
if [$? -eq 0]; then
应该是 if [ $? -eq 0 ]; then
done 之前的 fi
应该移到 for 循环之外。
示例:
array=(192.168.xxx.xxx 192.168.xxx.xxx)
ping -c 1 192.168.xxx.xxx
if [ $? -eq 0 ]; then
exit 0
else
for devices in "${array[@]}";do
ping -c 1 $devices &> /dev/null
if [ $? -eq 0 ]; then
exit 0
fi
done
fi
改进建议:
双引号是一个好习惯
if [[ $? -eq 0 ]]; then
的使用优于bash
中的if [ $? -eq 0 ]; then
一些评论:
#!/bin/bash
array=(192.168.xxx.xxx 192.168.xxx.xxx)
# a way to simplify first if:
ping -c 1 192.168.xxx.xxx && exit 0
for devices in "${array[@]}"; do
# you want send mail if ping is ok
if ping -c 1 $devices &> /dev/null; then
/usr/sbin/sendmail foo@bar.com < /home/pi/scripts/email.txt
exit 0
fi
done
我想在我的 raspi 上 运行 一个 bash 脚本。 该脚本的目的是检查我网络中的一台设备的可用性(使用 ping)。
如果此设备正在响应,脚本应该结束。 如果它没有响应,它必须进一步检查 3 个特定设备的可用性:如果这 3 个设备中的一个正在响应,则发送邮件;如果这些设备中的 none 有响应,则什么都不做。
我希望我到目前为止所做的是可识别的:
#!/bin/bash
array=(192.168.xxx.xxx 192.168.xxx.xxx)
ping -c 1 192.168.xxx.xxx
if [$? -eq 0]; then exit 0
else
for devices in "${array[@]}"
do ping -c 1 $devices &> /dev/null
if [ $? -eq 0 ]; then exit 0
fi
fi
done
/usr/sbin/sendmail foo@bar.com < /home/pi/scripts/email.txt
我现在很卡,因为我的脚本技术差得吓人。
您的代码中有两个错误:
if [$? -eq 0]; then
应该是if [ $? -eq 0 ]; then
done 之前的
fi
应该移到 for 循环之外。
示例:
array=(192.168.xxx.xxx 192.168.xxx.xxx)
ping -c 1 192.168.xxx.xxx
if [ $? -eq 0 ]; then
exit 0
else
for devices in "${array[@]}";do
ping -c 1 $devices &> /dev/null
if [ $? -eq 0 ]; then
exit 0
fi
done
fi
改进建议:
双引号是一个好习惯
if [[ $? -eq 0 ]]; then
的使用优于bash 中的
if [ $? -eq 0 ]; then
一些评论:
#!/bin/bash
array=(192.168.xxx.xxx 192.168.xxx.xxx)
# a way to simplify first if:
ping -c 1 192.168.xxx.xxx && exit 0
for devices in "${array[@]}"; do
# you want send mail if ping is ok
if ping -c 1 $devices &> /dev/null; then
/usr/sbin/sendmail foo@bar.com < /home/pi/scripts/email.txt
exit 0
fi
done