下面是一个简单的shell 脚本去判断输入的IP是否正常,然后进行ping测试
note: egrep 是grep的扩展,支持正则表达式,= grep -E
对于如何加while循环重复输入IP直至正确的步骤还没想好,欢迎大家给建议:)
#!/bin/bash
#The little script is used to test if a given IP online.
#1.check if the $1 is the format of IP.
#2.check if the IP can be ping with ok.
#check if IP is valid:
checkip()
{
echo $1 > /tmp/testip.txt
if echo $1 | egrep -q "^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$"
then
n1=`echo $1 | awk -F. '{print $1}'`
n2=`echo $1 | awk -F. '{print $2}'`
n3=`echo $1 | awk -F. '{print $3}'`
n4=`echo $1 | awk -F. '{print $4}'`
echo $n1 $n2 $n3 $n4
fi
#check if numbers are in 0-255.
for n in $n1 $n2 $n3 $n4; do
if [ $n -ge 255 ] || [ $n -le 0 ]; then
echo "The decimal numbers in IP is not correct, please check!" && exit
fi
done
}
#check if IP is ping with OK.
pingip()
{
ping -c 3 -i 0.2 -W 3 $1 &> /dev/null
if
[ $? -eq 0 ]
then
echo "The IP: $1 is online!"
else
echo "Unreachable IP!"
fi
}
read -p "Please input a IPv4 here:" IPADDR
checkip $IPADDR && pingip $IPADDR
文章有参考如下:
编写shell脚本,判断输入的IP是否正确
请问如何用shell的正则表达式判断一个数是否为IP地址 Shell脚本 IP验证