shell脚本-shell的getops

写一个getinterface.sh脚本可以接受选项[i,I],完成下面任务:

  • 使用一下形式:getinterface.sh [-i interface | -I ip]

  • 当用户使用-i选项时,显示指定网卡的IP地址;当用户使用-I选项时,显示其指定ip所属的网卡。
    例:
    sh getinterface.sh -i eth0
    sh getinterface.sh -I 192.168.0.1

  • 当用户使用除[-i | -I]选项时,显示[-i interface | -I ip]此信息。

  • 当用户指定信息不符合时,显示错误。(比如指定的eth0没有,而是eth1时)

#!/bin/bash
##Find ip or interface
##Written by Adai 2017-09-06
read -p "Input 'i' to interface;'I' to ip: " c
if [[ $c == i ]]
then
    read -p "Please input your interface name: " n
    ip=`ifconfig | egrep -A1 "$n" |egrep -v "$n" |awk '{print $2}'`
    echo "ip is: $ip"
elif [[ $c == I ]]
then
    read -p "Please input your ip:" m
    ens=`ifconfig | egrep -B1 "$m" |egrep -v "$m"|awk -F ":" '{print $1}'`
    echo "interface is: $ens"
else
    echo "Unknown variate.Please check your option!"
fi

铭哥:

#!/bin/bash
ip add |awk -F ":" '$1 ~ /^[1-9]/ {print $2}'|sed 's/ //g' > /tmp/eths.txt
[ -f /tmp/eth_ip.log ] && rm -f /tmp/eth_ip.log
for eth in `cat /tmp/eths.txt`
do
    ip=`ip add |grep -A2 ": $eth" |grep inet |awk '{print $2}' |cut -d '/' -f 1`
    echo "$eth:$ip" >> /tmp/eth_ip.log
done

useage()
{
    echo "Please useage: $0 -i 网卡名字 or $0 -I ip地址"
}

wrong_eth()
{
    if ! grep -q "$1" /tmp/eth_ip.log
    then
        echo "请指定正确的网卡名字"
    exit
    fi
}

wrong_ip()
{
    if ! grep -qw "$1" /tmp/eth_ip.log
    then
        echo "请指定正确的ip地址"
    exit
    fi
}

if [ $# -ne 2 ]
then
    useage
    exit
fi

case $1 in
    -i)
    wrong_eth $2 
    grep $2 /tmp/eth_ip.log |awk -F ':' '{print $2}'
    ;;

    -I)
    wrong_ip $2
    grep $2 /tmp/eth_ip.log |awk -F ':' '{print $1}'
    ;;

    *)
    useage
    exit
esac

转载于:https://my.oschina.net/adailinux/blog/1537623

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值