2017-12-04 3 views
0

getopt呼び出しを関数に入れてスクリプトを少しきちんと整えることができます。私はいくつかのガイドUsing getopts inside a Bash functionを読んだが、彼らはgetoptsではないgetoptsのようであり、私の頭の中でそれを得ることができない。私は、関数内で全体の多くを置くときBASH getopt in bash関数

私は私のスクリプトの開始

#------------------------------------------------------------------------------- 
# Main 
#------------------------------------------------------------------------------- 
getopt_results=$(getopt -s bash -o e:h --long ENVIRONMENT:,HELP:: -- "[email protected]") 

if test $? != 0 
then 
    echo "Failed to parse command line unrecognized option" >&2 
    Usage 
    exit 1 
fi 

eval set -- "$getopt_results" 

while true 
do 
    case "$1" in 
     -e | --ENVIRONMENT) 
      ENVIRONMENT="$2" 
      if [ ! -f "../properties/static/build_static.${ENVIRONMENT}.properties" -o ! -f "../properties/dynamic/build_dynamic.${ENVIRONMENT}.properties" ]; then 
      echo "ERROR: Unable to open properties file for ${ENVIRONMENT}" 
      echo "Please check they exist or supply a Correct Environment name" 
      Usage 
      exit 1 
      else 
      declare -A props 
      readpropsfile "../properties/dynamic/dynamic.${ENVIRONMENT}.properties" 
      readpropsfile "../properties/static/static.${ENVIRONMENT}.properties" 
      fi 
      shift 2 
      ;; 
     -h | --HELP) 
      Usage 
      exit 1 
    ;; 
     --) 
     shift 
     break 
     ;; 
     *) 
     echo "$0: unparseable option $1" 
     Usage 
     exit 1 
     ;; 
    esac 
done 

で次のgetoptの呼び出しを持って、parse_command_line() と呼ばれ、それがうまくできないため、私のスクリプトが死ぬparse_command_line "[email protected]" でそれを呼び出すと言います呼び出されたパラメータ私はいくつかのガイドに従ってOPTINDをローカルにしようとしました。何かアドバイス?ありがとう。

+2

は、あなたが書いている*正確な*機能を表示し、*正確な*エラーまたは結果が表示されます。 – chepner

+1

[BashFAQ#35](http://mywiki.wooledge.org/BashFAQ/035#getopts)、特に 'getopt' **を使用しない**の警告(最下部付近)を参照してください。 –

+1

関数で 'set-arg arg arg'を実行すると、**グローバル**位置パラメータではなく** function **の位置パラメータが設定されることに注意してください。 'getopt_results = $(parse_command_line" $ @ ");を実行する必要があります。 eval set - "$ getopt_results" 'そしてあなたは今よりもずっとやさしくはありません。 –

答えて

1

getoptは使用すべきではないが、以下に示すようbashの対応のGNU版は、関数内で正常に動作します:

#!/usr/bin/env bash 

main() { 
    local getopt_results 
    getopt_results=$(getopt -s bash -o e:h --long ENVIRONMENT:,HELP:: "[email protected]") 

    eval "set -- $getopt_results" # this is less misleading than the original form 

    echo "Positional arguments remaining:" 
    if (($#)); then 
     printf ' - %q\n' "[email protected]" 
    else 
     echo " (none)" 
    fi 
} 

main "[email protected]" 

...などgetopt-testと実行として保存する場合:

./getopt -e foo=bar "first argument" "second argument" 

は...適切に発する:

Positional arguments remaining: 
- -e 
- foo=bar 
- -- 
- hello 
- cruel 
- world