shell脚本中的getopts的使用

回复 收藏

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

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

2)当用户使用-i选项时,显示指定网卡的IP地址;当用户使用-I选项时,显示其指定ip所属的网卡。

例:sh getinterface.sh -i eth0

       sh getinterface.sh -I 192.168.0.1

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

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

2016-01-25 14:27 举报
已邀请:
0

zyos

赞同来自:

{:4_107:}
0

落涧飞鹰

赞同来自:

看看
0

thedawn

赞同来自:

1
0

maria

赞同来自:

look 一下
0

亮亮

赞同来自:

+1
0

rolay8

赞同来自:


  1. #/bin/bash

  2. case $1 in
  3. -i)
  4.     files=`find /etc/sysconfig/network-scripts/ -type f |grep $2`
  5.     if [ $? -ne 0 ];then
  6.         echo "There is no this $2!"
  7.     fi
  8.     for file in $files;do
  9.         grep "IPADDR" $file|awk -F "=" '{print $2}'
  10.     done
  11.     ;;
  12. -I)
  13.     files=`find /etc/sysconfig/network-scripts/ -type f -iname "ifcfg*"|xargs grep $2`
  14.     if [ $? -ne 0 ];then
  15.         echo "There is no this $2!"
  16.     fi
  17.     for file in $files;do
  18.         echo -n $file|awk -F "[-:]" '{print $3}'
  19.     done
  20.     ;;
  21. *)
  22.     echo "Usage [-i interface | -I ip]"
  23.     ;;

  24. esac
0

boy461205160

赞同来自:

{:4_91:}
0

1101066558

赞同来自:

#!/bin/bash

getopts "iI:" option
case $option in
-i)
        ifconfig $2 | grep -oP "(?<=inet addr:)\S+(?= )" | head -1
        ;;
-I)
        ifconfig
        ;;
*)
        echo "[-i interface | -I ip]"
        ;;
esac
0

我是学渣

赞同来自:

{:4_99:}
0

zhangzihao

赞同来自:

快快快
0

qiqige

赞同来自:

。。
0

wsw13640218682

赞同来自:

looklook
0

clq56688

赞同来自:

{:7_173:}
0

licengceng

赞同来自:

学习
0

xzzlamp

赞同来自:

11
0

mind_sky

赞同来自:

看看
0

elvis

赞同来自:

ddd
0

lin13750529011

赞同来自:

xiexie
0

linuxcp

赞同来自:

{:4_91:}
0

13805775620

赞同来自:

看看
0

阿铭 管理员

赞同来自:

#!/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

回复帖子,请先登录注册

退出全屏模式 全屏模式 回复
评分
可选评分理由: