getoptsの予期しない動作

getoptsの予期しない動作

考えると:

#!/bin/sh

while getopts ":h" o; do
  case "$o" in
    h )
    "Usage:
    sh $(basename "$0") -h      Displays help message
    sh $(basename "$0") arg     Outputs ...

     where:
    -h   help option
        arg  argument."
    exit 0
    ;;
    \? )
    echo "Invalid option -$OPTARG" 1>&2
    exit 1
    ;;
    : )
    echo "Invalid option -$OPTARG requires argument" 1>&2
    exit 1
    ;;
  esac
done

この呼び出しは何を返しますかnot found

$ sh getopts.sh -h
getopts.sh: 12: getopts.sh: Usage:
    sh getopts.sh -h        Displays help message
    sh getopts.sh arg   Outputs ...

     where:
    -h   help option
        arg  argument.: not found

いいね:

$ sh getopts.sh arg

これには「無効なオプション」が必要です。

$ sh getopts.sh

いいね:

$ sh getopts.sh -s x
Invalid option -s

ベストアンサー1

メッセージの印刷を見逃して、代わりに実行するコマンドで文字列全体を渡したようです。echo文字列の前にaを追加してください。

case "$o" in
  h )
  echo "Usage:
  sh $(basename "$0") -h      Displays help message
  sh $(basename "$0") arg     Outputs ...

   where:
  -h   help option
      arg  argument."
  exit 0
  ;;

ただし、通常、複数行の文字列を印刷する場合は、区切り文字を追加することをお勧めします。

show_help() {
cat <<'EOF'
Usage:
    sh $(basename "$0") -h      Displays help message
    sh $(basename "$0") arg     Outputs ...

     where:
    -h   help option
        arg  argument.
EOF
}

show_helpフラグに対応する機能を使用してください-h

また、空の引数フラグを使用すると、最初の呼び出しがループを終了するgetopts()ため、ループ内にハンドルを含めることはできません。呼び出す前に空のパラメータの一般的な確認getopts()

if [ "$#" -eq 0 ]; then
    printf 'no argument flags provided\n' >&2
    exit 1
fi

パラメータflagの以前の定義によれば、:hこれは-h許容されるパラメータがないことを示します。この句は、:)パラメータを取るように定義した場合、つまりとして定義されている場合にのみ適用されます。これで引数を渡さずに実行できます。以下のコードが実行されます。スクリプト全体を1つにまとめる-h:h::)

#!/usr/bin/env bash

if [ "$#" -eq 0 ]; then
    printf 'no argument flags provided\n' >&2
    exit 1
fi

show_help() {
cat <<'EOF'
Usage:
    sh $(basename "$0") -h      Displays help message
    sh $(basename "$0") arg     Outputs ...

     where:
    -h   help option
        arg  argument.
EOF
}

while getopts ":h:" opt; do
  case "$opt" in
    h )
    show_help
    exit 1
    ;;
    \? )
    echo "Invalid option -$OPTARG" 1>&2
    exit 1
    ;;
    : )
    echo "Invalid option -$OPTARG requires argument" 1>&2
    exit 1
    ;;
  esac
done

今実行

$ bash script.sh 
no argument flags provided
$ bash script.sh -h
Invalid option -h requires argument
$ bash script.sh -s
Invalid option -s

おすすめ記事