LoginSignup
5
7

More than 3 years have passed since last update.

シェルスクリプト getopts コマンド

Last updated at Posted at 2019-12-15

シェルスクリプトの引数をオプション付きで指定しするために使用します。
例えば、-c -v file arg のような形式のオプションを解析することができます。
この場合、-c は一文字のオプションで、-v は一文字のオプション + 引数(file)のような指定の仕方になります。

 1. 引数がすべてオプション形式での指定の場合

例として、abcが対応するオプションとしています。
オプション文字の直後に":"がある場合は、そのオプションが引数を必要としているものと判断されます。
aとbは引数を必要としないオプションになります。
cは引数を必要とするオプションになります。
対応していないオプションについては ? でキャッチして、エラーとして出力させています。

example1.sh
while getopts abc: option
do
  case $option in
    a)
      echo "This is option a.";;
    b)
      echo "This is option b.";;
    c)
      echo "This is option c with ${OPTARG}.";;
    \?)
      echo "This is unexpected option." 1>&2
      exit 1
  esac
done
result1.sh
$ ./example1.sh -a -b -c Hello -d
This is option a.
This is option b.
This is option c with Hello.
./example1.sh: illegal option -- d

 2. 引数にオプション形式以外のものが含まれる場合

オプション形式の引数を解析する部分は同じですが、その後に通常の引数を解釈させるためのコードを追加しています。
シェル変数 ${OPTIND} には、オプション形式ではない引数の最初の位置パラメータが入っているので、それ -1 の位置までパラメータをシフトしてあげます。

example2.sh
while getopts abc: option
do
  case $option in
    a)
      echo "This is option a.";;
    b)
      echo "This is option b.";;
    c)
      echo "This is option c with ${OPTARG}.";;
    \?)
      echo "This is unexpected option." 1>&2
      exit 1
  esac
done
echo ${OPTIND}
shift `expr "${OPTIND}" - 1`
if [ $# -ge 1 ]; then
  echo "Remaining options are $@."
else
  echo "No remaining options."
fi

以下の実行例の場合、Others がオプション形式以外の引数になりますが、引数の順番としては5つ目であり、${OPTIND}には 5 が入っているのが分かります。
そこまでシフトしてあげるために、5 - 1 = 4 つシフトしています。
オプション形式の引数を解析した後に、オプション形式以外の引数(残りの引数)を解析するという順番になります。
よって、先にオプション形式以外の引数を指定したり、それぞれを混在させるような指定はしません。

result2.sh
$ ./example2.sh -a -b -c Hello Other1 Other2
This is option a.
This is option b.
This is option c with Hello.
5
Remaining options are Other1 Other2.
5
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
7