カタカタブログ

SIerで働くITエンジニアがカタカタした記録を残す技術ブログ。Java, Oracle Database, Linuxが中心です。たまに数学やデータ分析なども。

いつも作るシェルスクリプトをテンプレート化してみた(オプション、引数チェック)

いつも作るシェルスクリプトをテンプレート化してみた(オプション、引数チェック)

bashでシェルスクリプトを書くと、オプションや引数チェックのロジックはいつもお決まりになるので、今回テンプレート化してみた。オプションと引数を解析して変数に格納、もし想定外のパラメータが入力された場合は使い方を標準エラー出力し、異常終了(exit 1)する、というもの。

作ったテンプレートはこちら。

template.sh

#!/bin/bash
# usage
cmdname=`basename $0`
function usage()
{
  echo "Usage: ${cmdname} [-t] [-f file] arg1 arg2" 1>&2
}

# check options
topt=FALSE
while getopts tf: option
do
  case ${option} in
    t)
      topt=TRUE
      ;;
    f)
      file=${OPTARG}
      ;;
    *)
      usage
      exit 1
      ;;
  esac
done
shift $((OPTIND - 1))

# check arguments
if [ $# -ne 2 ]; then
  usage
  exit 1
fi
arg1="$1"
arg2="$2"

# main
echo "arg1=[${arg1}], arg2=[${arg2}], topt=[${topt}], file=[${file}]"
exit 0

これを叩いてみるとこんなかんじ。

引数のみ

$ ./template.sh aaa bbb
arg1=[aaa], arg2=[bbb], topt=[FALSE], file=[]

パラメータ付き

$ ./template.sh -t -f file aaa bbb
arg1=[aaa], arg2=[bbb], topt=[TRUE], file=[file]

不正な入力の場合

$ ./template.sh
Usage: template.sh [-t] [-f file] arg1 arg2
$ ./template.sh aaa bbb ccc
Usage: template.sh [-t] [-f file] arg1 arg2
$ ./template.sh -f aaa bbb
Usage: template.sh [-t] [-f file] arg1 arg2

以上