getopts opstring name [arg …]
getopts は、標準 POSIX.2POSIX.2 オプション構文に続くパラメーターのリストからオプションとその引数 (先頭にハイフン (–) が付き、引数値が続くことがある単一文字) を取得します。 通常、シェル・スクリプトは、渡された引数を構文解析するため に getopts を使用します。 getopts コマンド行に arg 引数で 引数を指定すると、getopts はスクリプト・コマンド行の代わりに それらの引数を構文解析します (set を参照)。
getopts が疑問符 (?) を name に 入れるのは、opstring に現れないオプションを検出した場合、またはオプション value が欠落している場合です。
オプション文字の後に引数が続いている (opstring 内 の : で示される) 場合は、getopts は引数をストリングとして シェル変数 OPTARG に格納します。オプションが引数を取らない場合、または getopts が期待している引数を検出できなかった場合、getopts は OPTARG を設定解除します。
OPTIND および OPTARG は、シェル・スクリプトにローカルな変数です。これらをエクスポートしたい場合は、明示的に行う必要があります。スクリプトが getopts を 呼び出して OPTIND を 1 に設定した場合、新しいパラメーターのセット (現行の定位置パラメーター または新しい arg 値) を指定して、もう一度 getopts を呼び出すことができます。
デフォルトでは、認識できないオプションまたはその他のエラーを検出すると、getopts は エラー・メッセージを出します。このようなメッセージを印刷したくない場合は 、opstring の最初の文字としてコロンを指定してください。
# Example illustrating use of getopts builtin. This
# shell script would implement the paste command,
# using getopts to process options, if the underlying
# functionality was embedded in hypothetical utilities
# hpaste and vpaste, which perform horizontal and
# vertical pasting respectively.
#
paste=vpaste # default is vertical pasting
seplist=" " # default separator is tab
while getopts d:s o
do case "$o" in
d) seplist="$OPTARG";;
s) paste=hpaste;;
[?]) print >&2 "Usage: $0 [-s] [-d seplist] file …"
exit 1;;
esac
done
shift $OPTIND-1
# perform actual paste command
$paste -d "$seplist" "$@"
getopts は組み込みシェル・コマンドです。
POSIX.2, X/Open 移植性ガイド.
UNIX システムでは、getopts は Korn シェルと Bourne シェルの 両方に組み込まれています。
sh