在bash 中常常會利用 -a -b 之類的parameter對 function 下參數
ex:
$doA -a -b -c
getopts
可以用內建function getopts 達到
但限制是 -x的x只能single character
-somethhing就不能用這個方式
用法:
getopts optstring name
ex: getopts ":ab:c" optval
optstring
其中第一個引數
":ab:c"
第一個:表示未定義的options會被歸類為?,如果沒有這個:,不在list中的option都會導致error
a,c表示a,c是合法option
$ doA -a
$ doA -c
都是合法的
b:表示是合法帶參數的option, b的參數會存到"$OPTARG"
中 用法是
$ doA -b 123
此時
$echo $OPTARG
會得到 123
name
OPTIND
Used with while loop to get all opts
do
case $optval in
a)
echo "a"
;;
b)
echo "b" $OPTARG
;;
?)
echo "?"
;;
esac
done
Other way
more flexible, can handle --option with more world in option
sample code:
while true; do
case "$1" in
--opt1) OPT_opt1=1; shift ;;
--opt2) OPT_opt2="$2"; shift 2 ;;
--) shift; break ;;
-*) break ;;
*)
if [ -z "$1" ];then
break
fi
echo "$1 is not support"; usage; return 1;;
esac
done
沒有留言:
張貼留言