getopt/getopts:Bash中命令行選項/參數處理

 

0.引言


   寫程序的時候常常要處理命令行參數,本文描述在Bash下的命令行處理方式。
   選項與參數:
   以下一個命令行: shell

./test.sh -f config.conf -v --prefix=/home

咱們稱-f爲選項,它須要一個參數,即config.conf, -v 也是一個選項,但它不須要參數。 數組

   --prefix咱們稱之爲一個長選項,即選項自己多於一個字符,它也須要一個參數,用等號鏈接,固然等號不是必須的,/home能夠直接寫在--prefix後面,即--prefix/home,更多的限制後面具體會講到。
   在bash中,能夠用如下三種方式來處理命令行參數,每種方式都有本身的應用場景。 bash

    * 手工處理方式
    * getopts
    * getopt 函數

   下面咱們依次討論這三種處理方式。 spa

1. 手工處理方式

   在手工處理方式中,首先要知道幾個變量,仍是以上面的命令行爲例: 命令行

    *    $0 : ./test.sh,即命令自己,至關於C/C++中的argv[0]
    *    $1 : -f,第一個參數.
    *    $2 : config.conf
    *    $3, $4 ... :類推。
    *    $#  參數的個數,不包括命令自己,上例中$#爲4.
    *    $@ :參數自己的列表,也不包括命令自己,如上例爲 -f config.conf -v --prefix=/home
    *    $* :和$@相同,但"$*" 和 "$@"(加引號)並不一樣,"$*"將全部的參數解釋成一個字符串,而"$@"是一個參數數組。以下例所示: code

#!/bin/bash

for arg in "$*"
do
    echo $arg
done

for arg in "$@"
do
    echo $arg
done

執行./test.sh -f config.conf -n 10 會打印:

-f config.conf -n 10    #這是"$*"的輸出

-f   #如下爲$@的輸出

config.conf

-n

10 ip

因此,手工處理的方式即對這些變量的處理。由於手工處理高度依賴於你在命令行上所傳參數的位置,因此通常都只用來處理較簡單的參數。如

   ./test.sh 10 

   而不多使用./test -n 10這種帶選項的方式。 典型用法爲:
字符串

#!/bin/bash

if [ x$1 != x ]
then
    #...有參數
else
then
    #...沒有參數
fi



爲何要使用 x$1 != x 這種方式來比較呢?想像一下這種方式比較:


if [ -n $1 ]  #$1不爲空

但若是用戶不傳參數的時候,$1爲空,這時 就會變成 [ -n ] ,因此須要加一個輔助字符串來進行比較。

手工處理方式能知足大多數的簡單需求,配合shift使用也能構造出強大的功能,但在要處理複雜選項的時候建議用下面的兩種方法。
 
get

2. getopts/getopt


處理命令行參數是一個類似而又複雜的事情,爲此,C提供了getopt/getopt_long等函數,
C++的boost提供了Options庫,在shell中,處理此事的是getopts和getopt.

getopts和getopt功能類似但又不徹底相同,其中getopt是獨立的可執行文件,而getopts是由Bash內置的。

先來看看參數傳遞的典型用法:

    * ./test.sh -a -b -c  : 短選項,各選項不需參數
    * ./test.sh -abc   : 短選項,和上一種方法的效果同樣,只是將全部的選項寫在一塊兒。
    * ./test.sh -a args -b -c :短選項,其中-a須要參數,而-b -c不需參數。
    * ./test.sh --a-long=args --b-long :長選項

咱們先來看getopts,它不支持長選項。

使用getopts很是簡單:

#test.sh

#!/bin/bash

while getopts "a:bc" arg #選項後面的冒號表示該選項須要參數
do
        case $arg in
             a)
                echo "a's arg:$OPTARG" #參數存在$OPTARG中
                ;;
             b)
                echo "b"
                ;;
             c)
                echo "c"
                ;;
             ?)  #當有不認識的選項的時候arg爲?
            echo "unkonw argument"
        exit 1
        ;;



如今就可使用:
./test.sh -a arg -b -c 

./test.sh -a arg -bc
來加載了。
應該說絕大多數腳本使用該函數就能夠了,若是須要支持長選項以及可選參數,那麼就須要使用getopt.
下面是getopt自帶的一個例子:

#!/bin/bash

# A small example program for using the new getopt(1) program.
# This program will only work with bash(1)
# An similar program using the tcsh(1) script language can be found
# as parse.tcsh

# Example input and output (from the bash prompt):
# ./parse.bash -a par1 'another arg' --c-long 'wow!*\?' -cmore -b " very long "
# Option a
# Option c, no argument
# Option c, argument `more'
# Option b, argument ` very long '
# Remaining arguments:
# --> `par1'
# --> `another arg'
# --> `wow!*\?'

# Note that we use `"$@"' to let each command-line parameter expand to a
# separate word. The quotes around `$@' are essential!
# We need TEMP as the `eval set --' would nuke the return value of getopt.

#-o表示短選項,兩個冒號表示該選項有一個可選參數,可選參數必須緊貼選項
#如-carg 而不能是-c arg
#--long表示長選項
#"$@"在上面解釋過
# -n:出錯時的信息
# -- :舉一個例子比較好理解:
#咱們要建立一個名字爲 "-f"的目錄你會怎麼辦?
# mkdir -f #不成功,由於-f會被mkdir看成選項來解析,這時就可使用
# mkdir -- -f 這樣-f就不會被做爲選項。

TEMP=`getopt -o ab:c:: --long a-long,b-long:,c-long:: \
     -n 'example.bash' -- "$@"`

if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi

# Note the quotes around `$TEMP': they are essential!
#set 會從新排列參數的順序,也就是改變$1,$2...$n的值,這些值在getopt中從新排列過了
eval set -- "$TEMP"

#通過getopt的處理,下面處理具體選項。

while true ; do
        case "$1" in
                -a|--a-long) echo "Option a" ; shift ;;
                -b|--b-long) echo "Option b, argument \`$2'" ; shift 2 ;;
                -c|--c-long)
                        # c has an optional argument. As we are in quoted mode,
                        # an empty parameter will be generated if its optional
                        # argument is not found.
                        case "$2" in
                                "") echo "Option c, no argument"; shift 2 ;;
                                *)  echo "Option c, argument \`$2'" ; shift 2 ;;
                        esac ;;
                --) shift ; break ;;
                *) echo "Internal error!" ; exit 1 ;;
        esac
done
echo "Remaining arguments:"
for arg do
   echo '--> '"\`$arg'" ;
done



好比咱們使用
./test -a  -b arg arg1 -c 
你能夠看到,命令行中多了個arg1參數,在通過getopt和set以後,命令行會變爲:
-a -b arg -c -- arg1
$1指向-a,$2指向-b,$3指向arg,$4指向-c,$5指向--,而多出的arg1則被放到了最後。

3.總結

通常小腳本手工處理也許就夠了,getopts能處理絕大多數的狀況,getopt較複雜,功能也更強大。

相關文章
相關標籤/搜索