今回利用するコマンドはgetoptsです。コマンドのgetoptsではありません。
getoptsは、bashのビルドインコマンドです。
以下にgetoptsの使いかたを説明します。
getopts ":abc"
先頭に:が存在する場合は、abc以外のオプションが来た場合のエラー処理を自ら記述することを意味します。
#!/bin/bash
# filename: getopts-1.sh
while getopts ":abc" opts
do
case $opts in
a)
echo a
;;
b)
echo b
;;
c)
echo c
;;
esac
done
実行結果
$ ./getopts-1.sh -abc a b c $ ./getopts-1.sh -a -b -c a b c先頭に:があるためエラー出力されません。
$ ./getopts-1.sh -d $
#!/bin/bash
# filename: getopts-2.sh
while getopts "abc" opts
do
case $opts in
a)
echo a
;;
b)
echo b
;;
c)
echo c
;;
esac
done
実行結果
$ ./getopts-2.sh -abcd a b c ./getopts-2.sh: illegal option -- d
後ろに:がある場合は、オプションの後ろに引数があるを指定します。
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-4.sh -z What is -z option???\?)に記述された処理が実行されています。
$ ./getopts-4.sh -f Option -f requires an argument !!!:)に記述された処理が実行されています。
getoptsには、以下の変数があります。
OPTARGについては上記のサンプルシェルスクリプトで使用しています。
処理対象のオプションが格納されています。
OPTERRの初期値は1になります。
この値を0にするとgetoptsからのエラー出力を抑止できます。
以下のサンプルシェルスクリプトで説明します。
#!/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
$ ./getopts-5.sh -z Initial value: OPTERR=1 ./getopts-5.sh: illegal option -- zgetoptsの引数の先頭に:がないのでgetoptsによりエラー処理が実行されているのがわかります。
$ ./getopts-5.sh -f -z Initial value: OPTERR=1上記は最初に-fオプションを指定しOPTERRの値を0にしています。
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
$ ./getopts-6.sh -abc a OPTIND value is 1 b OPTIND value is 1 c OPTIND value is 2
$ ./getopts-6.sh -a -b -c a OPTIND value is 2 b OPTIND value is 3 c OPTIND value is 4上記の結果よりOPTINDは引数の位置を管理しています。
OPTINDを使う場面は以下のような場合です。
#!/bin/bash
# filename: getopts-7.sh
while getopts "abc" opts
do
case $opts in
a)
;;
b)
;;
c)
;;
esac
done
shift `expr $OPTIND - 1`
echo $*
実行結果
$ ./getopts-7.sh -a -b -c sakura sakura
shiftコマンドによりgetoptsで処理されたオプションが消されsakuraだけが残ります。
したがって、getopts以外で使用する引数がある場合などは、OPTINDとshiftを使うことにより引数を残すことができます。
以下のように記述することもできます。
shift $((OPTIND-1)) # shift `expr $OPTIND - 1`