Bashのスクリプトパラメータ

Bashのスクリプトパラメータ

私は2つのスクリプトパラメータを取得し、スクリプトで変数として使用するスクリプトを開発しています。私はこれを動作させることができず、何が間違っているのかわかりません。問題は2番目のパラメータであることがわかります。一部のテストで見たように(この記事の下部に記載されているように)読み取られません。

コードは次のとおりです。

    #!usr/bin/bash


help()
{
   echo ""
    echo "Usage: $0 -p patch_level -e environment"
    echo -e "\t-p Patch level that you are tryin to update the server"
    echo -e "\t-e Environment that the patch need to be run on"
   exit 1 # Exit script after printing help
}


while getopts "p:e" opt
do
   case "${opt}" in
      p ) patch_level="$OPTARG" ;;
      e ) _env="$OPTARG" ;;
      ? ) help ;;    # Print help in case parameter is non-existent

   esac
done


if [ -z "$patch_level" ] || [ -z "$_env" ];    # checking for null parameter
then
   echo "Some or all of the parameters are empty";
   help
else
   echo "$patch_level and $_env"
fi

以下のスクリプトを実行すると、この結果が得られます。

> ./restart.sh -p 2021 -e sbx 
>  Some or all of the parameters are empty
> Usage: ./restart.sh -p patch_level -e environment
>         -p Patch level that you are tryin to update the server
>         -e Environment that the patch need to be run on

注:私はこの記事の3番目の答えに基づいてコードをモデル化しました。

コマンドラインパラメータをシェルスクリプトに渡すには?

問題は2番目の変数(-e)にあることがわかりました。なぜなら、最後のif文を「or」から「and」に変更するとスクリプトが実行されますが、2番目の変数については何も印刷しないからです。

それが私が言いたいのです。

if [ -z "$patch_level" ] && [ -z "$_env" ];

出力は次のとおりです

./restart.sh -p 2021 -e sbx
  2021 and
 This server will be patched to 2021

それが重要であれば、私はUbuntuにいます。

ベストアンサー1

$_envパラメータをに渡した方法で設定されていませんgetopts

オプションに引数が必要であることをe知らせるには、オプションの後にコロンを追加する必要があります。getopts

while getopts "p:e:" op
                  ^
              mandatory here

確認する:

help getopts | less

おすすめ記事