2010-11-26 77 views
1

我使用以下腳本:在bash中檢查getopts狀態的最佳方法是什麼?

#!/bin/bash 
#script to print quality of man 
#unnikrishnan 24/Nov/2010 
shopt -s -o nounset 
declare -rx SCRIPT=${0##*/} 
declare -r OPTSTRING="hm:q:" 
declare SWITCH 
declare MAN 
declare QUALITY 
if [ $# -eq 0 ];then 
printf "%s -h for more information\n" "$SCRIPT" 
exit 192 
fi 
while getopts "$OPTSTRING" SWITCH;do 
case "$SWITCH" in 
h) printf "%s\n" "Usage $SCRIPT -h -m MAN-NAME -q MAN-QUALITY" 
    exit 0 
    ;; 
m) MAN="$OPTARG" 
    ;; 
q) QUALITY="$OPTARG" 
    ;; 
\?) printf "%s\n" "Invalid option" 
    printf "%s\n" "$SWITCH" 
    exit 192 
    ;; 
*) printf "%s\n" "Invalid argument" 
    exit 192 
    ;; 
esac 
done 
printf "%s is a %s boy\n" "$MAN" "$QUALITY" 
exit 0 

在這一點,如果我給垃圾選項:

./getopts.sh adsas 
./getopts.sh: line 32: MAN: unbound variable 

你可以看到它失敗。它似乎雖然不工作。什麼是解決它的最好方法。

回答

1

如果你確實需要男人,那麼我建議你不要讓一個選項參數,但一個位置參數。選項應該是可選的。

不過,如果你想這樣做,作爲一個選項,然後執行:

# initialise MAN to the empty string 
MAN= 
# loop as rewritten by DigitalRoss 
while getopts "$OPTSTRING" SWITCH "[email protected]"; do 
    case "$SWITCH" in 
    m) MAN="$OPTARG" ;; 
    esac 
done 
# check that you have a value for MAN 
[[ -n "$MAN" ]] || { echo "You must supply a MAN's name with -m"; exit 1; } 

更妙的是,在退出前打印用法消息 - 將其拉出到一個功能,所以您可以用分享 - h選項的情況。

0

「最好」的解決方案是主觀的。一種解決方案是將默認值賦予可由選項設置的變量。

2

當沒有選項參數時,內建函數getopts返回1(「false」)。

因此,您的while從不會執行,除非您有以-開頭的選項參數。

注意在bash的getopts的部分最後一段(1):

  getopts returns true if an option, specified or unspecified, is 
      found. It returns false if the end of options is encountered or 
      an error occurs. 
相關問題