doilux’s tech blog

ITに関する備忘録。 DDP : http://doiluxng.hatenablog.com/entry/2018/01/01/195409

shellスクリプトのテンプレート

オレオレシェルをつくるなら以下のテンプレートを使う。

#!/usr/bin/env zsh

# Settings
## スクリプト名
script=$(basename $0)

## バージョン
version="v1.0"

## debugモード(デフォルトoff)
debug=0

## 引数の数(オプションを除く)
args_num=1

# usageを表示
function show_usage_and_exit() {
  cat <<EOF
$script is a tool for ...

Usage:
  $script [<options>] [command]

Options:
  -d       execute debug mode
  -v       print $(basename ${0}) version
  -h       print this
EOF
  exit 0
}

# バージョン表示
function show_version_and_exit() {
  echo $version
  exit 0
}

# メイン関数
function main() {
  chk_args $@
  echo $1
  exit 0
}

# debugログ出力
function log() {
  if [ $debug -eq 1 ]; then
    echo "[DEBUG]" $@
  fi
}

# 引数チェック
function chk_args() {
  if [ $# -ne $args_num ]; then
    log "argment check error"
    echo "Too meny arguments"
    echo "see help:"
    echo "   ${script} -h"
    exit 1
  fi
}


while getopts "vhd" OPT
do
  case $OPT in
    v)
      show_version_and_exit
      ;;
    h)
      show_usage_and_exit
      ;;
    d)
      debug=1
      ;;
    \?)
      show_usage_and_exit
      ;;
  esac
done

# 引数リストからオプションを除外する
shift `expr $OPTIND - 1`

# メイン関数の実行
main $@