1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ChatGPT への口頭試問(シェルスクリプトのオプション解析コードの生成)

Last updated at Posted at 2025-04-24

こんにちは。
シェルスクリプトの使用方法の記述からオプション解析コードを生成するという課題で、ChatGPT へ口頭試問を行い1、概ね優れた回答をもらいました。

ChatGPT への質問

次の使用方法の記述から、シェルスクリプトのオプション解析コードを作ってください。なお POSIX 準拠、かつ getopt や getopts は使用しないでください。

  Name: $PROGNAME - parse arguments$LF
  Usage: $PROGNAME [options] [__argument__...]$LF
  Options:
    -h|--help       Print this usage and exit.
    -d|--debug      Set debug mode.
    -n|--number __number__  Set non-negative integer (default: $number_var)
    -m|--mammal __name__    Set mammal name.

ChatGPT からの回答

了解しました!以下は POSIX 準拠 かつ getopt や getopts を使わずに、純粋に shift と case を使って手動でオプションを解析するシェルスクリプトです。

#!/bin/sh

PROGNAME=$(basename "$0")
LF='
'

# デフォルト値
debug=0
number_var=0
mammal_name=""
positional_args=""

print_usage() {
  cat <<EOF
Name: $PROGNAME - parse arguments$LF
Usage: $PROGNAME [options] [__argument__...]$LF
Options:
  -h|--help            Print this usage and exit.
  -d|--debug           Set debug mode.
  -n|--number __number__   Set non-negative integer (default: $number_var)
  -m|--mammal __name__     Set mammal name.
EOF
}

# オプション解析開始
while [ "$#" -gt 0 ]; do
  case "$1" in
    -h|--help)
      print_usage
      exit 0
      ;;
    -d|--debug)
      debug=1
      shift
      ;;
    -n|--number)
      shift
      if [ -z "$1" ] || ! echo "$1" | grep -Eq '^[0-9]+$'; then
        echo "Error: --number requires a non-negative integer." >&2
        exit 1
      fi
      number_var=$1
      shift
      ;;
    -m|--mammal)
      shift
      if [ -z "$1" ]; then
        echo "Error: --mammal requires a name." >&2
        exit 1
      fi
      mammal_name=$1
      shift
      ;;
    --) # 明示的な区切りがあった場合
      shift
      break
      ;;
    -*) # 不正なオプション
      echo "Unknown option: $1" >&2
      exit 1
      ;;
    *)  # オプション以外(位置引数)
      break
      ;;
  esac
done

# 残りは位置引数
positional_args="$@"

# デバッグ表示
if [ "$debug" -eq 1 ]; then
  echo "Debug mode: $debug"
  echo "Number: $number_var"
  echo "Mammal: $mammal_name"
  echo "Positional arguments: $positional_args"
fi
  1. これは「ChatGPT への口頭試問(docopts)」の続編です。

1
1
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?