8
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

シェルスクリプトでgetoptsを使ったことなかったので調べてみた

8
Posted at

getoptsはBashのシェルスクリプト内で引数解析ができる組み込みコマンドです。
manコマンドの内容を抜粋してみると以下のようになっています。

manコマンド抜粋
getopts optstring name [arg ...]
getopts  is used by shell procedures to parse positional parameters.  optstring contains the option characters to be recognized; if a char‐acter is followed by a colon, the option is expected to have an argument, which should be separated from it by white space.
Google翻訳
getopts は、シェルプロシージャが位置パラメータを解析するために使用されます。optstring には、認識されるオプション文字が含まれます。文字の後にコロンが続く場合、そのオプションには引数が必要であり、引数は空白で区切る必要があります。

動かしてみる

-uと-nの引数を取得する例を動かしてみました。

example1.sh
#!/bin/bash
username=""
number=""

while getopts u:n: OPT
do
  case ${OPT} in
    u)
      username="${OPTARG}"
    ;;
    n)
      number="${OPTARG}"
    ;;
    ?)
      echo "Unexpected args"
      exit 1
    ;;
  esac
done

echo "USERNAME: ${username}"
echo "NUMBER: ${number}"
実行例1
$ ./example1.sh -u hoge -n 100
USERNAME: hoge
NUMBER: 100

今回は-uと-nの後の引数値を取得しているので、optstring ではuとnの後にコロンが付きます。

スクリプト抜粋
while getopts u:n: OPT

想定外の引数はエラーが出力されます。
case文では?の処理が走ります。

実行例2
$ ./example1.sh -u hoge -n 100 -x
./example1.sh: illegal option -- x
Unexpected args
スクリプト抜粋
    ?)
      echo "Unexpected args"
      exit 1
    ;;

optstringの先頭にコロンを追記すると、illegal optionが出力されなくなります。

example2.sh
#!/bin/bash
username=""
number=""

while getopts :u:n: OPT
do
  case ${OPT} in
    u)
      username="${OPTARG}"
    ;;
    n)
      number="${OPTARG}"
    ;;
    ?)
      echo "Unexpected args"
      exit 1
    ;;
  esac
done

echo "USERNAME: ${username}"
echo "NUMBER: ${number}"
diff example1.sh example2.sh
6c6
< while getopts u:n: OPT
---
> while getopts :u:n: OPT
実行例3
$ ./example2.sh -u hoge -n 100 -x
Unexpected args

コロンを記載しない場合は引数の値が取得されないです。
引数の有無は判定できるので、値が不要なパラメータに利用できます。

example3.sh
#!/bin/bash
username=""
number=""

while getopts u:n OPT
do
  case ${OPT} in
    u)
      username="${OPTARG}"
    ;;
    n)
      echo "n args sets"
      number="${OPTARG}"
    ;;
    ?)
      echo "Unexpected args"
      exit 1
    ;;
  esac
done

echo "USERNAME: ${username}"
echo "NUMBER: ${number}"
実行例4
$ ./example3.sh -u hoge -n 100
n args sets
USERNAME: hoge
NUMBER:
8
1
1

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
8
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?