一、只从文件读取
[root@rhel8 shell]# cat ping.sh
#!/bin/bash
# 判断是否有输入参数
if [ $# -eq 0 ];then
# basename:只输出路劲的最后一个名称
echo -e "\033[34mUsage: `basename $0` filename.txt\033[0m"
fi
# 判断是否输入的是文件
if [ ! -f $1 ];then
echo -e "\033[33mError file(It‘s not a file)\033[0m"
exit
fi
# 从文件读取ip地址
for ip in `cat $1`
do
ping -c2 $ip >/dev/null 2>&1
if [ $? -eq 0 ];then
echo -e "\033[33m${ip} is up\033[0m"
else
echo -e "\033[33m${ip} is down\033[0m"
fi
done
二、从命令行或文件读取
[root@rhel8 shell]# cat ping.sh
#!/bin/bash
IP_REG=([0-9]{1,3}\.){3}[0-9]{1,3}
# 判断是否有输入参数
if [ $# -eq 0 ];then
# basename:只输出路劲的最后一个名称
echo -e "\033[34mUsage: `basename $0` filename.txt|ipaddr\033[0m"
exit
fi
# 判断是$1是否输入参数,输入的参数是ip地址还是文件
# 判断输入的是IP地址
if [[ $1 =~ $IP_REG ]];then
ping -c2 -W1 $1 >/dev/null 2>&1
if [ $? -eq 0 ];then
echo -e "\033[33m$1 is up\033[0m"
else
echo -e "\033[33m$1 is down\033[0m"
fi
elif [ -f $1 ];then
# 从文件读取ip地址
for ip in `cat $1`
do
ping -c2 $ip >/dev/null 2>&1
if [ $? -eq 0 ];then
echo -e "\033[33m${ip} is up\033[0m"
else
echo -e "\033[33m${ip} is down\033[0m"
fi
done
else
# basename:只输出路径的最后一个名称
echo -e "\033[34mUsage: `basename $0` filename.txt|ipaddr\033[0m"
exit
fi