2011-10-04 78 views
3

什麼是最簡單,最直接的使用方法getopts in bash腳本。你如何使用getopts?

,如果我有一個名爲腳本:的MyScriptCAN取的參數:-p -r -s -x

if argument x then exit 
if argument p then echo "port 10" 
if argument s then add 2+2 
if argument r then echo env 

這是一個假設的腳本,但我只想喜歡看這樣做的例子。 [在bash shell腳本使用getopts的獲得長期和短期的命令行選項]的

+0

可能重複(http://stackoverflow.com/questions/402377/using-getopts-in-bash-shell -script-to-get-long-and-short-command-line-options) – 2011-10-04 13:46:43

+0

我看過它,沒有幫助我。謝謝你指出,雖然 – stackoverflow

回答

9
while getopts :xpsr opt; do 
    case $opt in 
    x) exit        ;; 
    p) echo port 10      ;; 
    s) ((2 + 2))       ;; 
    r) echo env       ;; 
    \?) echo "${0##*/}" [ -xpsr ]; exit 1 ;; 
    esac 
done 
+0

甜..感謝Dimitre。但是這最後一部分是做什麼的? \? )echo「$ {0 ## * /}」[-xpsr];退出1 – stackoverflow

+1

打印使用情況並在傳遞無效選項時存在。 –

+0

你不會展示如何處理其餘的論點...... –

3
usage() 
{ 
    echo "Usage: $0 [-o <offset>] [-h];" 
    exit 0; 
} 

# -o (offset) need a value 
# -h prints help 
offset=0 # 0 is default offset 

while getopts o:s opt 
do 
    case "$opt" in 
    d) offset="$OPTARG";; # changing offset 
    s) usage    # calls function "usage" 
    \?) echo "$OPTARG is an unknown option" 
     exit 1;; # all other options 
    esac 
done 

shift $((OPTIND-1)) 
+1

在哪個shell中轉換$ OPTIND-1表達式工作?它通常必須是'$(($ OPTIND - 1))',不是。 –

+1

甚至:'$((OPTIND - 1))',這是現在的標準。 –

+0

我修好了,對不起 –