我的腳本中有以下命令:
set -- `getopt -q agvc:l:t:i: "$@"`
...
while [ -n "$1" ]
do
-i) TIME_GAP_BOOT=$2
shift ;;
...
sleep $TIME_GAP_BOOT
使用 呼叫腳本時-i 2
,出現錯誤
sleep: invalid time interval `\'2\''
我究竟做錯了什麼?如何正確格式化參數?
答案1
內建的 bashgetopts
更容易使用。如果您正在使用bash
,則應該使用它而不是getopt
。
GNUgetopt
設計用於處理其中包含空格和其他元字元的參數。為此,它會產生一個帶有 bash 樣式引號(或 csh 樣式引號,取決於選項-s
)的結果字串eval
。 (我有沒有提到 bash 內建函數getopts
比較好?)。
以下範例來自 getopt 發行版;我與此無關。 (它應該出現在你機器上的某個地方;對於 ubuntu 和 debian,它顯示為/usr/share/doc/util-linux/examples/getopt-parse.bash
。我只引用幾行:
# 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.
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!
eval set -- "$TEMP"
除了範例註解所指向的引號之外,檢視 也很重要eval
,它通常不受歡迎。
相比之下,bash 內建指令getopts
不需要eval
,而且非常簡單;它基本上模擬了標準 C 庫呼叫:
while getopts agvc:l:t:i: opt; do
case "$opt" in
i) TIME_GAP_BOOT=$OPTARG;;
# ...
esac
done