コンテンツにスキップ

bash スクリプトでショート/ロングオプションの両方を扱う

bash スクリプトで引数を扱うには getopts を利用します。 ショートオプション/ロングオプションの両方を扱う場合のスクリプト例をメモしておきます。

サンプルスクリプト

#!/usr/bin/env bash

function base() {
    echo base
}

function full() {
    echo full
}

while getopts ":b-:" opt; do
    case "$opt" in
        -)
            case "${OPTARG}" in
                base)
                    base
                    exit
                    ;;
            esac
            ;;
        b)
            base
            exit
            ;;
    esac
done

base
full

実行例

# ./sample.sh
base
full
# ./sample.sh -b
base
# ./sample.sh --base
base