2017年最新企业面试题之shell(二)



练习题1:
写一个shell脚本,将192.169.5.0/24网段在线的ip列出来。(找出活动ip)

要求如下:

1.将在线ip与不在线ip分别放在两个文件中,方便后期查阅;

2.不影响对当前终端进行操作;

3.脚本运行结束后,给予提示信息,表明脚本已经运行结束。

脚本内容如下:

方法一:

#!/bin/bash
[ -f /etc/init.d/functions ] && . /etc/init.d/functions||exit1
# 验证系统函数文件是否存在,如存在则调用系统函数,否则退出!
ips="192.169.5."
for i in $(seq 254)
do
ping -c 2 $ips$i >/dev/null 2>/dev/null
if [ "$?" == "0" ]
then
        echo "echo $ips$i is online" >>/root/ip_online.txt
else
        echo "echo $ips$i is not online" >>/root/ip_noline.txt
fi
done
if [ "$ips$i" != "192.169.5.255" ];then
        action "shell脚本执行完毕!" /bin/true
fi

方法二:

#!/bin/bash
[ -f /etc/init.d/functions ] && . /etc/init.d/functions||exit1 
# 验证系统函数文件是否存在,如存在则调用系统函数,否则退出!
for ip in $(cat /root/ip.txt)
do
ping -c 2 $ip >/dev/null 2>/dev/null
if [ "$?" == "0" ]
then
        echo "echo $ip is online" >>/root/ip_online.txt
else
        echo "echo $ip is not online" >>/root/ip_noline.txt
fi
done
if [ "$ip" != "192.169.5.255" ];then
        action "shell脚本执行完毕!" /bin/true
fi

说明:

(1)如果脚本名字 ip_online.sh ,则执行脚本时为不影响当前终端的使用,使用 sh ip_online.sh &命令执行。

(2)不建议使用方法二,因为编辑/root/ip.txt文件太浪费时间。