基本パラメータ解析部分

基本パラメータ解析部分

-hなどのヘルプオプションやその他のオプションを追加するbashスクリプトを作成しました。--help--verbose

説明通りに作るとこここれが標準的なソリューションになるのでしょうか?

# Execute getopt on the arguments passed to this program, identified by the special character $@
PARSED_OPTIONS=$(getopt -n "$0"  -o h123: --long "help,one,two,three:"  -- "$@")

#Bad arguments, something has gone wrong with the getopt command.
if [ $? -ne 0 ];
then
  exit 1
fi

# A little magic, necessary when using getopt.
eval set -- "$PARSED_OPTIONS"


# Now goes through all the options with a case and using shift to analyse 1 argument at a time.
#$1 identifies the first argument, and when we use shift we discard the first argument, so $2 becomes $1 and goes again through the case.
while true;
do
  case "$1" in

    -h|--help)
      echo "usage $0 -h -1 -2 -3 or $0 --help --one --two --three"
     shift;;

    -1|--one)
      echo "One"
      shift;;

    -2|--two)
      echo "Dos"
      shift;;

    -3|--three)
      echo "Tre"

      # We need to take the option of the argument "three"
      if [ -n "$2" ];
      then
        echo "Argument: $2"
      fi
      shift 2;;

    --)
      shift
      break;;
  esac
done

それともこれを達成するための別の定義された方法はありますか?

ベストアンサー1

case実際、シェルスクリプタはあなたと非常によく似た方法でステートメントを使用して独自のパラメータ解析を作成するのが一般的です。今、それが最高のソリューションか最も標準的なソリューションであるかは議論の余地があります。個人的にCの経験のためにgetopt

getopt.1マニュアルページから:

getoptは、シェルプロセスがオプションを簡単に解析し、適切なオプションを確認できるように、コマンドラインからオプションを分析(分析)するために使用されます。これを行うには、GNU getopt(3)ルーチンを使用します。

あなたが電話をしたならばgetopt、あなたは間違いなく正しい道を行っていると言いたいと思います。必要に応じて、ステートメントを使用してコマンドライン引数を繰り返すことでcaseこれらのケースを処理できますが、すでに知っているように、getopt実際にはすべての重い操作を実行します。


重要な要約:これはシェルスクリプトなので、好きな方法で実装できますが、getopt便利です。

おすすめ記事