Shellで簡易的なコマンドツールを開発

スポンサーリンク

Shellコマンドをベースに簡易的なコマンドツールを作る機会があったので、その方法の覚書を記します。

目的

Shellコマンド群を組み合わせ、簡易的なコマンドツールを作成します。
コマンドツールに必要な引数、オプションの指定に加え、ヘルプの表示に対応します。

コマンドのベースを作成

引数の取得

コマンド実行に必ず必要なパラメータを取得する際に利用します。
引数に渡す順番で値を判断します。

  • コード
ARGS1=$1
ARGS2=$2

echo $ARGS1
echo $ARGS2
  • 実行結果
$./example args1 args2
args1
args2

オプションの取得

コマンド実行のための補助的なパラメータを取得する際に利用します。

  • コード
OPTIONAL=""
IS_TRUE=false
POS=()

while [[ $# -gt 0 ]]
do
key="$1"

case $key in
    # パラメータが必要なオプションの場合、取得するパラメータの数+1回shiftする
    -o|--optional)
    OPTIONAL=$2
    shift
    shift
    ;;
    # パラメータが不要なオプションの場合、shiftを1回行う
    -i|--is-true)
    IS_TRUE=true
    shift
    ;;
    *)
    POS+=("$1")
    shift
    ;;
esac
done
# 引数のポジションを元に戻す
set -- "${POS[@]}"

echo $OPTIONAL
echo $IS_TRUE
  • 実行結果
$./example --optional option --is-true
option
true

$./example --optional option
option
false

ヘルプの作成

引数が足りない場合やヘルプオプションが指定された際にヘルプを表示します。

  • コード
HELP=`cat << EOF
Usage: example [ARGS1] [OPTIONS]...

Args1:
  Args1 is an example argument.

Options:
  -h, --help  Show this message and exit.
EOF`

ARGS1=$1
POS=()

while [[ $# -gt 0 ]]
do
key="$1"

case $key in
    -h|--help)
    echo "$HELP"
    exit
    ;;
    *)
    POSITIONAL+=("$1")
    shift
    ;;
esac
done

if [ "$ARGS1" = "" ]; then
    echo "$HELP"
    exit
fi

echo $ARGS1
  • 実行結果
$./example
Usage: example [ARGS1] [OPTIONS]...

Args1:
  Args1 is an example argument.

Options:
  -h, --help  Show this message and exit.

$./example example
example

$./example --help
Usage: example [ARGS1] [OPTIONS]...

Args1:
  Args1 is an example argument.

Options:
  -h, --help  Show this message and exit.

あとがき

これらの方法を合わせたテンプレートをGithubに上げているので、必要な方はこちらを参照ください。

GitHub - fealone/bash-base-command-sample: This repository is a bash base command sample.
This repository is a bash base command sample. Contribute to fealone/bash-base-command-sample development by creating an account on GitHub.