shell习题-获取ip


提示用户输入网卡的名字,然后我们用脚本输出网卡的ip。 看似简单,但是需要考虑多个方面,比如我们输入的不符合网卡名字的规范,怎么应对。名字符合规范,但是根本就没有这个网卡有怎么应对。

 

参考答案:

#!/bin/bash
while :
do
     read -p "请输入网卡名: " e
     e1=`echo "$e" | sed 's/[-0-9]//g'`
     e2=`echo "$e" | sed 's/[a-zA-Z]//g'`
     if [ -z $e ]
     then
        echo "你没有输入任何东西"
        continue
     elif [ -z $e1 ]
     then
        echo "不要输入纯数字在centos中网卡名是以eth开头后面加数字"
        continue
     elif [ -z $e2 ]
     then
        echo "不要输入纯字母在centos中网卡名是以eth开头后面加数字"
        continue
     else
        break
     fi
done

ip() {
        ifconfig | grep -A1 "$1 " |tail -1 | awk '{print $2}' | awk -F ":" '{print $2}'
}

myip=`ip $e`
if [ -z $myip ]
then
    echo "抱歉,没有这个网卡。"
else
    echo "你的网卡IP地址是$myip"
fi