getoptsを利用して引数を取得する(bashビルドイン) †今回利用するコマンドはgetoptsです。コマンドのgetopt 関連資料 †bashビルドインのgetoptsについて †以下にgetoptsの使いかたを説明します。 getopts引数:先頭の:の意味 †getopts ":abc" 先頭に:が存在する場合は、abc以外のオプションが来た場合のエラー処理を自ら記述することを意味します。
getopts引数:後ろの:の意味 †後ろに:がある場合は、オプションの後ろに引数があるを指定します。 getopts "abf:" #!/bin/bash # filename: getopts-3.sh while getopts "abf:" opts do case $opts in a) echo a ;; b) echo b ;; f) TARGET_FILE=$OPTARG ;; esac done if [ "$TARGET_FILE" != "" ]; then echo TARGET = $TARGET_FILE fi 実行結果 $ ./getopts-3.sh -a -f foo.txt a TARGET = foo.txt $ ./getopts-3.sh -fbar.txt TARGET = bar.txt $ ./getopts-3.sh -f ./getopts-3.sh: option requires an argument -- f 自分でエラー処理をする場合 †先頭に:を付けることによりオプションのエラー処理を自ら記述しなけらばなりません。 #!/bin/bash # filename: getopts-4.sh while getopts ":af:" opts do case $opts in a) echo a ;; f) TARGET_FILE=$OPTARG ;; :) echo "Option -$OPTARG requires an argument !!!" >&2 ;; ¥?) echo "What is -$OPTARG option ???" >&2 ;; esac done if [ "$TARGET_FILE" != "" ]; then echo TARGET = $TARGET_FILE fi 実行結果
getoptsの変数 †getoptsには、以下の変数があります。
OPTARGの説明 †OPTARGについては上記のサンプルシェルスクリプトで使用しています。 OPTERRの説明 †OPTERRの初期値は1になります。 #!/bin/bash # filename: getopts-5.sh echo Initial value: OPTERR=$OPTERR while getopts "af" opts do case $opts in a) echo a ;; f) OPTERR=0 ;; esac done
OPTINDの説明 †OPTINDの値を表示する簡単なシェルスクリプト #!/bin/bash # filename: getopts-6.sh while getopts "abc" opts do case $opts in a) echo a ;; b) echo b ;; c) echo c ;; esac echo OPTIND value is $OPTIND done
OPTINDを使う場面は以下のような場合です。
shiftコマンドによりgetoptsで処理されたオプションが消されsakuraだけが残ります。 shift $((OPTIND-1)) # shift `expr $OPTIND - 1` |