2023年3月31日 星期五

[bash] 在function中用 getopts 取得 options

在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

getopts 會把引數存到 $name
ex: $ doA -a
$ getopts "a" optval
$ echo $optval
會印出 a

OPTIND

getopts每被呼叫一次,就會去取下一個參數,這部份是用$OPTIND在控制的
因此在function中使用時,記得將OPTIND設成local否則多次進入會有問題
$local OPTIND
$getopts ":abc" optval
 
** 在function中使用因為function會多次被呼叫,有跟外部共用變數空間,要記得將$OPTIND設定成local

Used with  while loop to get all opts

sample code:
 
    local optval OPTIND
    
    while getopts ":ab:c" optval
    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
 


沒有留言:

張貼留言