1.getopts "ab" OPT
表示后面可接选项为-a或-b,并将最后一个选项赋值给OPT变量
a.sh内容为:
#!/bin/sh
getopts "ab" OPT
echo $OPT
输出为:
[root@test0 shell]# sh a.sh -a
a
[root@test0 shell]# sh a.sh -b
b
[root@test0 shell]# sh a.sh -a -b
a
2.getopts "a:b:" OPT
表示后面可接选项为 -a arg,-b arg,并将选项赋值给OPT,arg赋值给内置变量OPTARG
a.sh内容为:
#!/bin/sh
getopts "a:b:" OPT
echo $OPT
echo $OPTARG
 
[root@test0 shell]# sh a.sh -a "hehe"
a
hehe
[root@test0 shell]# sh a.sh -b "nini"
b
nini
3.getopts ":a:b:" OPT
a前面的:为忽略错误信息
4.当要执行多个选项时,用while语句
a.sh内容为:
#!/bin/sh
while getopts "a:b:" OPT
do
        case $OPT in
        a) echo "the option is a"
           echo $OPTARG ;;
        b) echo "the option is b"
           echo $OPTARG ;;
        \?) echo "wrong" ;;
        esac
done
 
输出:
[root@test0 shell]# sh a.sh -b "nini"
the option is b
nini
[root@test0 shell]# sh a.sh -b "nini" -a "cc"
the option is b
nini
the option is a
cc
[root@test0 shell]# sh a.sh -b "nini" -a "cc" -d
the option is b
nini
the option is a
cc
a.sh: illegal option -- d
wrong
 
5.内置变量OPTIND为指向选项参数数量+1的值,若选项和参数总数为5,那么OPTIND为6
a.sh内容为:
#!/bin/sh
while getopts "a:b:" OPT
do
        case $OPT in
        a) echo "the option is a"
           echo $OPTARG 
           echo $OPTIND ;;
        b) echo "the option is b"
           echo $OPTARG 
        echo $OPTIND ;;
        \?) echo "wrong" 
        echo $OPTIND ;;
        esac
done
 
输出为:
[root@test0 shell]# sh a.sh  -d
a.sh: illegal option -- d
wrong
2
 
[root@test0 shell]# sh a.sh -b "nini" -a "cc" -d
the option is b
nini
3
the option is a
cc
5
a.sh: illegal option -- d
wrong
6
 
 
 
下面为马哥教育上面一例子,自己做的,经测试,能实现基本的功能,当然仅是做学习测试,有很多还不完善的地方,如-I后面的IP判断,一些不正常输入等
题:
1)使用以下形式:getinterface.sh [-i interface|-I IP|-a]
2)当用户使用-i选项时,显示其指定的网卡IP地址
3)当用户使用-I选项时,显示其后面的IP地址所属的网络接口
4)当用户单独使用-a选项时,显示所有网络接口及其IP地址(lo除外)
#!/bin/sh
getopts ":i:I:a" SWIT
case $SWIT in
i)
        echo "the interface is $OPTARG"
        ifconfig "$OPTARG"|grep "inet addr"|awk -F: '{print $2}'|sed  's/Bcast//g'
        ;;
I)
        echo "the IP is $OPTARG"
        ifconfig|grep  -B 1 -e "$OPTARG"|awk '{print $1}'|grep "^eth"
        ;;
a)
        /sbin/ip addr|grep inet|grep -v 127|grep -v inet6|awk '{print $NF":"$2}'
        ;;
\?)     echo "Usage:$0 [-i interface|-I IP|-a]"
        ;;
esac