LoginSignup
46
34

More than 5 years have passed since last update.

bashでロングオプションとショートオプションの両方に対応する

Last updated at Posted at 2016-05-04

getoptsを利用します。
getoptsの引数の後ろに:をつけるとOPTARG変数にその値が保持されるので、-の後ろにつけてロングオプションに対応します。

sample.sh
#!/bin/bash

help() {
    echo help
}

version() {
    echo version
}

while getopts ":vh-:" opt; do
    case "$opt" in
        -)
            case "${OPTARG}" in
                help)
                    help
                    ;;
                version)
                    version
                    ;;
            esac
            ;;
        h)
            help
            ;;
        v)
            version
            ;;
    esac
done

実行

$ ./sample --help
help
$ ./sample -h
help
$ ./sample --version
version
$ ./sample -v
version

以下の記事を参考にさせていただきました。

bash によるオプション解析 - Qiita

46
34
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
46
34