動かざることバグの如し

近づきたいよ 君の理想に

シェルスクリプトで引数オプションをパースするテンプレート作った

なんだかんだ言ってシェルスクリプトはどの環境でも動くから自作スクリプトを走らせるにはbashが一番だったりする。 しかしlinux系コマンドでよくある

./exe.sh -i hoge.txt -o out.txt -a

みたいなオプションを自分で1から実装するのはつらい。そこでgetoptsコマンドを使ったオプションを読み込む

#!/bin/sh

function usage {

  cat <<EOM
Usage: $(basename "$0") [OPTION]...

  -a VALUE    argument description
  -b VALUE    argument description
  -c          switch description
  -d          switch description
  -h          display help
EOM

  exit 2
}

# init switch flags
c=0
d=0

while getopts ":a:b:cdh" optKey; do
  case "$optKey" in
    a)
      a=$OPTARG
      ;;
    b)
      b=$OPTARG
      ;;
    c)
      c=1
      ;;
    d)
      d=1
      ;;
    h|*)
      usage
      ;;
  esac
done

echo a=$a
echo b=$b
echo c=$c
echo d=$d

あとでかくn