shell中獲取參數能夠直接使用$一、$2等形式來獲取,但這種方式有明顯的限制:每一個參數的位置是固定的。好比若是在設計上$1是ip地址$2是端口,那在執行時就必須第一個參數是ip第二個參數是端口而不能反過來。html
shell提供了getopt和getopts來解析參數,getopt比getopts功能強一些getopts比getopt簡單一些;整體而言getopt和getopts都差強人意。git
getopt比getopts強一些複雜一些:能在命令行中單獨使用、支持長選項格式、支持選項值可選。更多說明見註釋。github
#/bin/bash usage(){ echo " Usage: -i, --ip target server ip -p, --port target service port -h, --help display this help and exit example1: testGetopt -i192.168.1.1 -p80 example2: testGetopt --ip=192.168.1.1 --port=80 " # 短格式中,選項值爲可選的選項,選項值只能緊接選項而不可以使用任何符號將其餘選項隔開;如-p80,不要寫成性-p 80 # 短格式中,選項值爲必有的選項,選項值既可緊接選項也可使用空格與選項隔開;如-i192.168.1.1,也可寫成-i 192.168.1.1 # 長格式中,選項值爲可選的選項,選項值只能使用=號鏈接選項;如--port=80,不可寫成性--port80或--port 80 # 長格式中,選項值爲必有的選項,選項值既可以使用=號鏈接選項也可以使用空格鏈接選項;如--ip=192.168.1.1,也可寫成--ip 192.168.1.1 # 爲簡便起見,建議凡是短格式都使用「選項+選項值」的形式(-p80),凡是長格式都使用「選項+=+選項值」的形式(--port=80) } main(){ while true do case "$1" in -i|--ip) ip="$2" echo "ip: $ip" shift ;; -p|--port) port="$2" echo "port: $port" shift ;; -h|--help) usage # 打印usage以後直接用exit退出程序
exit ;; --) shift break ;; *) echo "$1 is not option" ;; esac shift done # 剩餘全部未解析到的參數存在$@中,可經過遍歷$@來獲取 #for param in "$@" #do # echo "Parameter #$count: $param" #done } # 若是隻註冊短格式能夠以下這樣子 # set -- $(getopt i:p::h "$@") # 若是要註冊長格式須要以下這樣子 # -o註冊短格式選項 # --long註冊長格式選項 # 選項後接一個冒號表示其後爲其參數值,選項後接兩個冒號表示其後能夠有也能夠沒有選項值,選項後沒有冒號表示其後不是其參數值 set -- $(getopt -o i:p::h --long ip:,port::,help -- "$@") # 因爲是在main函數中才實現參數處理,因此須要使用$@將全部參數傳到main函數 main $@
持行效果:shell
參考:bash
https://blog.csdn.net/wh211212/article/details/53750366函數
http://yejinxin.github.io/parse-shell-options-with-getopt-commandthis
getopts比getopt弱一些簡單一些:不能在命令行中單獨使用、不支持長選項格式、不支持選項值可選。更多說明見註釋。spa
#!/bin/bash usage(){ echo " Usage: -i, --ip target server ip -p, --port target service port -h, --help display this help and exit example1: ./testGetopts.sh -i192.168.1.1 -p80 example2: ./testGetopts.sh -i 192.168.1.1 -p 80 " # getopts只能在shell腳本中使用,不能像getopt同樣在命令行中單獨使用 # getopts只支持短格式不支持長格式 # getopts若是設定有選項值的選項,若是沒提供選項值那麼會直接報錯 # getopts選項要麼有選項值要麼沒有選項值,沒有可有也能夠沒有 # getopts選項後可緊接選項值,也可使用空格隔開;爲與getopt統一建議使用緊接格式 } main(){ # 選項有:表示該選項須要選項值 while getopts "i:p:h" arg do case $arg in i) #參數存在$OPTARG中 ip="$OPTARG" echo "ip: $ip" ;; p) port="$OPTARG" echo "port: $port" ;; h) usage
# 打印usage以後直接用exit退出程序
exit ;; ?) #當有不認識的選項的時候arg值爲? echo "unregistered argument" exit 1 ;; esac done } main $@
執行效果:.net
參考:命令行
https://www.cnblogs.com/FrankTan/archive/2010/03/01/1634516.html