0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

オプション引数解析を行うシェルスクリプトコードを生成

0
Last updated at Posted at 2026-05-08

こんにちは。
オプション引数解析を行うシェルスクリプトコードを生成する機能を持つ、シェルスクリプトを作りました(generate_parser.sh1

入力データ

入力データ例として下記形式のオプション定義を用います。

OPTIONS="Options:
  -h, --help         Show this usage and exit. (variable 'help_enabled')
  -d, --debug        Enable debug mode. (variable 'debug_enabled')
  -l, --loops N      Set the number of loops. (variable 'loops_var')
  -m, --mammal NAME  Set mammal name. (variable 'mammal_var')
"

コード生成および実行

上記の入力を用いた例です。

$ echo "$OPTIONS" | ./generate_parser.sh > arg_parse.sh; chmod u+x arg_parse.sh
$ ./arg_parse.sh -xy --loops
Warning:
- unknown option: -x
- unknown option: -y
- missing value for --loops

下記のコードが生成されます。ただし可読性は良くないです2

$ cat arg_parse.sh
#!/bin/sh
TRUE="true"
warning=""
append_warning_f() { [ -z "$warning" ] && warning="$1" || warning="$warning$(printf "\n%s" "$1")"; }

# parse optional arguments
while [ $# -gt 0 ]; do
  case "$1" in
    -h|--help) help_enabled=$TRUE;;
    -d|--debug) debug_enabled=$TRUE;;
    -l|--loops) [ $# -ge 2 ] && [ "${2#-}" = "$2" ] && { loops_var=$2; shift; } || append_warning_f "missing value for $1";;
    -l*|--loops=*) loops_var="$1"; for p in -l --loops=; do loops_var="${loops_var#"$p"}"; done;;
    -m|--mammal) [ $# -ge 2 ] && [ "${2#-}" = "$2" ] && { mammal_var=$2; shift; } || append_warning_f "missing value for $1";;
    -m*|--mammal=*) mammal_var="$1"; for p in -m --mammal=; do mammal_var="${mammal_var#"$p"}"; done;;
    -[!-][!-]*) rest_flags=${1#??}; first_flag="${1%"$rest_flags"}"; shift; set -- "$first_flag" "-$rest_flags" "$@"; continue;;
    --) shift; break;;
    -*) append_warning_f "unknown option: $1";;
    *) break;;
  esac
  shift
done

[ -n "$warning" ] && { printf "%s\n" "Warning:"; printf '%s\n' "$warning" | sed 's/^/- /' >&2; exit 1; }

source code

  1. これによって生成されるコード自体の特徴および制約条件はこちらと同一です:「シェルスクリプトの簡素なオプション引数解析」。

  2. 可読性をもう少し良くしたいならば、こちらの方が良さそうです:「シェルスクリプトの簡素なオプション引数解析

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?