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