BASH bash 函数中的 getopt

BASH getopt inside bash function

我想将我的 getopt 调用放入一个函数中,这样我可以使我的脚本更整洁一些。我已经阅读了一些指南 Using getopts inside a Bash function,但它们似乎是针对 getopts 而不是 getopt 的,我无法理解。

我在脚本开头有以下 getopt 调用

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

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 "" in
      -e | --ENVIRONMENT)
          ENVIRONMENT=""
          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 "[=12=]: unparseable option "
         Usage
         exit 1
         ;;
  esac
done

当我把全部都放在函数中时,说叫 parse_command_line () 并用 parse_command_line "$@" 调用它 我的脚本死了,因为它无法计算出调用时使用的参数。我已经尝试根据一些指南将 OPTIND 设为本地。有什么建议吗?谢谢。

getopt 不应该被使用,但是 bash-aware GNU 版本在函数内部工作正常,如下所示:

#!/usr/bin/env bash

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

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

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

main "$@"

...当另存为 getopt-test 和 运行 时:

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

...正确发出:

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