如何在 bash 中使用 getopts 的示例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16483119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 23:41:53  来源:igfitidea点击:

An example of how to use getopts in bash

bashshellgetopts

提问by MOHAMED

I want to call myscriptfile in this way:

我想以myscript这种方式调用文件:

$ ./myscript -s 45 -p any_string

or

或者

$ ./myscript -h  #should display help
$ ./myscript     #should display help

My requirements are:

我的要求是:

  • getopthere to get the input arguments
  • check that -sexists, if not return an error
  • check that the value after the -sis 45 or 90
  • check that the -pexists and there is an input string after
  • if the user enters ./myscript -hor just ./myscriptthen display help
  • getopt在这里获取输入参数
  • 检查是否-s存在,如果不存在则返回错误
  • 检查 后的值-s是否为 45 或 90
  • 检查是否-p存在并且之后有一个输入字符串
  • 如果用户输入./myscript -h或刚刚./myscript显示帮助

I tried so far this code:

到目前为止,我试过这段代码:

#!/bin/bash
while getopts "h:s:" arg; do
  case $arg in
    h)
      echo "usage" 
      ;;
    s)
      strength=$OPTARG
      echo $strength
      ;;
  esac
done

But with that code I get errors. How to do it with Bash and getopt?

但是使用该代码我会出错。如何使用 Bash 和getopt?

回答by Adrian Frühwirth

#!/bin/bash

usage() { echo "Usage: 
$ ./myscript.sh
Usage: ./myscript.sh [-s <45|90>] [-p <string>]

$ ./myscript.sh -h
Usage: ./myscript.sh [-s <45|90>] [-p <string>]

$ ./myscript.sh -s "" -p ""
Usage: ./myscript.sh [-s <45|90>] [-p <string>]

$ ./myscript.sh -s 10 -p foo
Usage: ./myscript.sh [-s <45|90>] [-p <string>]

$ ./myscript.sh -s 45 -p foo
s = 45
p = foo

$ ./myscript.sh -s 90 -p bar
s = 90
p = bar
[-s <45|90>] [-p <string>]" 1>&2; exit 1; } while getopts ":s:p:" o; do case "${o}" in s) s=${OPTARG} ((s == 45 || s == 90)) || usage ;; p) p=${OPTARG} ;; *) usage ;; esac done shift $((OPTIND-1)) if [ -z "${s}" ] || [ -z "${p}" ]; then usage fi echo "s = ${s}" echo "p = ${p}"

Example runs:

示例运行:

getopts OPTSTRING VARNAME [ARGS...]

回答by kenorb

The problem with the original code is that:

原代码的问题在于:

  • h:expects parameter where it shouldn't, so change it into just h(without colon)
  • to expect -p any_string, you need to add p:to the argument list
  • h:期望参数在它不应该的地方,所以把它改成只是h(没有冒号)
  • 期望-p any_string,您需要添加p:到参数列表

Basically :after the option means it requires the argument.

基本上:在选项之后意味着它需要参数。



The basic syntax of getoptsis (see: man bash):

的基本语法getopts是(见:)man bash

#!/usr/bin/env bash
usage() { echo "
$ ./foo.sh 
./foo.sh usage:
    p) # Specify p value.
    s) # Specify strength, either 45 or 90.
    h | *) # Display help.
$ ./foo.sh -s 123 -p any_string
Strength needs to be either 45 or 90, 123 found instead.
p is any_string
$ ./foo.sh -s 90 -p any_string
Strength is 90.
p is any_string
usage:" && grep " .)\ #"
getopt optstring parameters
; exit 0; } [ $# -eq 0 ] && usage while getopts ":hs:p:" arg; do case $arg in p) # Specify p value. echo "p is ${OPTARG}" ;; s) # Specify strength, either 45 or 90. strength=${OPTARG} [ $strength -eq 45 -o $strength -eq 90 ] \ && echo "Strength is $strength." \ || echo "Strength needs to be either 45 or 90, $strength found instead." ;; h | *) # Display help. usage exit 0 ;; esac done

where:

在哪里:

  • OPTSTRINGis string with list of expected arguments,

    • h- check for option -hwithoutparameters; gives error on unsupported options;
    • h:- check for option -hwithparameter; gives errors on unsupported options;
    • abc- check for options -a, -b, -c; giveserrors on unsupported options;
    • :abc- check for options -a, -b, -c; silenceserrors on unsupported options;

      Notes: In other words, colon in front of options allows you handle the errors in your code. Variable will contain ?in the case of unsupported option, :in the case of missing value.

  • OPTARG- is set to current argument value,

  • OPTERR- indicates if Bash should display error messages.
  • OPTSTRING是带有预期参数列表的字符串,

    • h- 检查-h没有参数的选项;在不支持的选项上给出错误;
    • h:- 检查-h参数的选项;在不支持的选项上给出错误;
    • abc- 检查选项-a, -b, -c; 在不支持的选项上给出错误;
    • :abc- 检查选项-a, -b, -c; 消除不受支持的选项的错误;

      注意:换句话说,选项前面的冒号允许您处理代码中的错误。变量将包含?在不支持选项:的情况下,在缺失值的情况下。

  • OPTARG- 设置为当前参数值,

  • OPTERR- 指示 Bash 是否应显示错误消息。

So the code can be:

所以代码可以是:

# This is correct
getopt "hv:t::" "-v 123 -t123"  
getopt "hv:t::" "-v123 -t123"  # -v and 123 doesn't have whitespace

# -h takes no value.
getopt "hv:t::" "-h -v123"


# This is wrong. after -t can't have whitespace.
# Only optional params cannot have whitespace between key and value
getopt "hv:t::" "-v 123 -t 123"

# Multiple arguments that takes value.
getopt "h:v:t::g::" "-h abc -v 123 -t21"

# Multiple arguments without value
# All of these are correct
getopt "hvt" "-htv"
getopt "hvt" "-h -t -v"
getopt "hvt" "-tv -h"

Example usage:

用法示例:

getopt [getopt_options] [--] [optstring] [parameters]

See: Small getopts tutorialat Bash Hackers Wiki

请参阅:Bash Hackers Wiki 上的Small getopts 教程

回答by theBuzzyCoder

Use getopt

getopt

Why getopt?

为什么是getopt?

To parse elaborated command-line arguments to avoid confusion and clarify the options we are parsing so that reader of the commands can understand what's happening.

解析详细的命令行参数以避免混淆并阐明我们正在解析的选项,以便命令的读者可以理解发生了什么。

What is getopt?

什么是getopt?

getoptis used to break up (parse) options in command lines for easy parsing by shell procedures, and to check for legal options. It uses the GNU getopt(3)routines to do this.

getopt用于分解(解析)命令行中的选项,以便 shell 过程轻松解析,并检查合法选项。它使用 GNUgetopt(3)例程来执行此操作。

getoptcan have following types of options.

getopt可以有以下类型的选项。

  1. No-value options
  2. key-value pair options
  1. 无价值选项
  2. 键值对选项

Note: In this document, during explaining syntax:

注意:在本文档中,在解释语法时:

  • Anything inside [ ] is optional parameter in the syntax/examples.
  • is a place holder, which mean it should be substituted with an actual value.
  • [] 内的任何内容都是语法/示例中的可选参数。
  • 是一个占位符,这意味着它应该用实际值代替。

HOW TO USE getopt?

如何使用getopt

Syntax: First Form

语法:第一种形式

getopt -l "name:,version::,verbose" -- "n:v::V" "--name=Karthik -version=5.2 -verbose"

Examples:

例子:

getopt [getopt_options] [-o options] [--] [optstring] [parameters]

Here h,v,t are the options and -h -v -t is how options should be given in command-line.

这里 h,v,t 是选项, -h -v -t 是在命令行中应该如何给出选项。

  1. 'h' is a no-value option.
  2. 'v:' implies that option -v has value and is a mandatory option. ':' means has a value.
  3. 't::' implies that option -t has value but is optional. '::' means optional.
  1. 'h' 是一个无值选项。
  2. 'v:' 意味着选项 -v 具有价值并且是强制性选项。':' 表示有值。
  3. 't::' 意味着选项 -t 有值但是可选的。'::' 表示可选。

In optional param, value cannot have whitespace separation with the option. So, in "-t123" example, -t is option 123 is value.

在可选参数中,值不能与选项有空格分隔。因此,在“-t123”示例中,-t 是选项 123 是值。

Syntax: Second Form

语法:第二种形式

getopt -l "name:,version::,verbose" -a -o "n:v::V" -- "-name=Karthik -version=5.2 -verbose"

Here after getopt is split into five parts

这里getopt之后分为五部分

  • The command itself i.e. getopt
  • The getopt_options, it describes how to parse the arguments. single dash long options, double dash options.
  • --, separates out the getopt_options from the options you want to parse and the allowed short options
  • The short options, is taken immediately after -- is found. Just like the Form first syntax.
  • The parameters, these are the options that you have passed into the program. The options you want to parse and get the actual values set on them.
  • 命令本身即 getopt
  • getopt_options,它描述了如何解析参数。单破折号长选项,双破折号选项。
  • --, 将 getopt_options 与要解析的选项和允许的短选项分开
  • 短选项在找到 -- 后立即执行。就像 Form first 语法一样。
  • 参数,这些是您传递给程序的选项。您要解析的选项并获取在它们上设置的实际值。

Examples

例子

getopt "name:,version" "--name=Karthik"

Syntax: Third Form

语法:第三种形式

getopt "name:,version" "-name=Karthik"

Here after getopt is split into five parts

这里getopt之后分为五部分

  • The command itself i.e. getopt
  • The getopt_options, it describes how to parse the arguments. single dash long options, double dash options.
  • The short options i.e. -o or --options. Just like the Form first syntax but with option "-o" and before the "--" (double dash).
  • --, separates out the getopt_options from the options you want to parse and the allowed short options
  • The parameters, these are the options that you have passed into the program. The options you want to parse and get the actual values set on them.
  • 命令本身即 getopt
  • getopt_options,它描述了如何解析参数。单破折号长选项,双破折号选项。
  • 短选项,即 -o 或 --options。就像 Form first 语法一样,但有选项“-o”和“--”(双破折号)之前。
  • --, 将 getopt_options 与要解析的选项和允许的短选项分开
  • 参数,这些是您传递给程序的选项。您要解析的选项并获取在它们上设置的实际值。

Examples

例子

#!/bin/bash

# filename: commandLine.sh
# author: @theBuzzyCoder

showHelp() {
# `cat << EOF` This means that cat should stop reading when EOF is detected
cat << EOF  
Usage: ./installer -v <espo-version> [-hrV]
Install Pre-requisites for EspoCRM with docker in Development mode

-h, -help,          --help                  Display help

-v, -espo-version,  --espo-version          Set and Download specific version of EspoCRM

-r, -rebuild,       --rebuild               Rebuild php vendor directory using composer and compiled css using grunt

-V, -verbose,       --verbose               Run script in verbose mode. Will print out each step of execution.

EOF
# EOF is found above and hence cat command stops reading. This is equivalent to echo but much neater when printing out.
}


export version=0
export verbose=0
export rebuilt=0

# $@ is all command line parameters passed to the script.
# -o is for short options like -v
# -l is for long options with double dash like --version
# the comma separates different long options
# -a is for long options with single dash like -version
options=$(getopt -l "help,version:,verbose,rebuild,dryrun" -o "hv:Vrd" -a -- "$@")

# set --:
# If no arguments follow this option, then the positional parameters are unset. Otherwise, the positional parameters 
# are set to the arguments, even if some of them begin with a ‘-'.
eval set -- "$options"

while true
do
case  in
-h|--help) 
    showHelp
    exit 0
    ;;
-v|--version) 
    shift
    export version=
    ;;
-V|--verbose)
    export verbose=1
    set -xv  # Set xtrace and verbose mode.
    ;;
-r|--rebuild)
    export rebuild=1
    ;;
--)
    shift
    break;;
esac
shift
done

GETOPT_OPTIONS

GETOPT_OPTIONS

getopt_options changes the way command-line params are parsed.

getopt_options 改变了命令行参数的解析方式。

Below are some of the getopt_options

下面是一些 getopt_options

Option: -l or --longoptions

选项:-l 或 --longoptions

Means getopt command should allow multi-character options to be recognised. Multiple options are separated by comma.

意味着 getopt 命令应该允许识别多字符选项。多个选项以逗号分隔。

For example, --name=Karthikis a long option sent in command line. In getopt, usage of long options are like

例如,--name=Karthik是在命令行中发送的长选项。在 getopt 中,长选项的使用就像

# With short options grouped together and long option
# With double dash '--version'

bash commandLine.sh --version=1.0 -rV
# With short options grouped together and long option
# With single dash '-version'

bash commandLine.sh -version=1.0 -rV

# OR with short option that takes value, value separated by whitespace
# by key

bash commandLine.sh -v 1.0 -rV

# OR with short option that takes value, value without whitespace
# separation from key.

bash commandLine.sh -v1.0 -rV

# OR Separating individual short options

bash commandLine.sh -v1.0 -r -V

Since name: is specified, the option should contain a value

由于 name: 被指定,该选项应该包含一个值

Option: -a or --alternative

选项:-a 或 --alternative

Means getopt command should allow long option to have a single dash '-' rather than double dash '--'.

意味着 getopt 命令应该允许长选项有一个单破折号“-”而不是双破折号“--”。

Example, instead of --name=Karthikyou could use just -name=Karthik

示例,而不是--name=Karthik您可以仅使用-name=Karthik

#!/bin/bash

# A small example program for using the new getopt(1) program.
# This program will only work with bash(1)
# An similar program using the tcsh(1) script language can be found
# as parse.tcsh

# Example input and output (from the bash prompt):
# ./parse.bash -a par1 'another arg' --c-long 'wow!*\?' -cmore -b " very long "
# Option a
# Option c, no argument
# Option c, argument `more'
# Option b, argument ` very long '
# Remaining arguments:
# --> `par1'
# --> `another arg'
# --> `wow!*\?'

# Note that we use `"$@"' to let each command-line parameter expand to a 
# separate word. The quotes around `$@' are essential!
# We need TEMP as the `eval set --' would nuke the return value of getopt.
TEMP=`getopt -o ab:c:: --long a-long,b-long:,c-long:: \
     -n 'example.bash' -- "$@"`

if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi

# Note the quotes around `$TEMP': they are essential!
eval set -- "$TEMP"

while true ; do
    case "" in
        -a|--a-long) echo "Option a" ; shift ;;
        -b|--b-long) echo "Option b, argument \`'" ; shift 2 ;;
        -c|--c-long) 
            # c has an optional argument. As we are in quoted mode,
            # an empty parameter will be generated if its optional
            # argument is not found.
            case "" in
                "") echo "Option c, no argument"; shift 2 ;;
                *)  echo "Option c, argument \`'" ; shift 2 ;;
            esac ;;
        --) shift ; break ;;
        *) echo "Internal error!" ; exit 1 ;;
    esac
done
echo "Remaining arguments:"
for arg do echo '--> '"\`$arg'" ; done

A complete script example with the code:

带有代码的完整脚本示例:

#!/bin/bash

function get_variable_name_for_option {
    local OPT_DESC=
    local OPTION=
    local VAR=$(echo ${OPT_DESC} | sed -e "s/.*\[\?-${OPTION} \([A-Z_]\+\).*//g" -e "s/.*\[\?-\(${OPTION}\).*/FLAG/g")

    if [[ "${VAR}" == "" ]]; then
        echo ""
    else
        echo ${VAR}
    fi
}

function parse_options {
    local OPT_DESC=
    local INPUT=$(get_input_for_getopts "${OPT_DESC}")

    shift
    while getopts ${INPUT} OPTION ${@};
    do
        [ ${OPTION} == "?" ] && usage
        VARNAME=$(get_variable_name_for_option "${OPT_DESC}" "${OPTION}")
            [ "${VARNAME}" != "" ] && eval "${VARNAME}=${OPTARG:-true}" # && printf "\t%s\n" "* Declaring ${VARNAME}=${!VARNAME} -- OPTIONS='$OPTION'"
    done

    check_for_required "${OPT_DESC}"

}

function check_for_required {
    local OPT_DESC=
    local REQUIRED=$(get_required "${OPT_DESC}" | sed -e "s/\://g")
    while test -n "${REQUIRED}"; do
        OPTION=${REQUIRED:0:1}
        VARNAME=$(get_variable_name_for_option "${OPT_DESC}" "${OPTION}")
                [ -z "${!VARNAME}" ] && printf "ERROR: %s\n" "Option -${OPTION} must been set." && usage
        REQUIRED=${REQUIRED:1}
    done
}

function get_input_for_getopts {
    local OPT_DESC=
    echo ${OPT_DESC} | sed -e "s/\([a-zA-Z]\) [A-Z_]\+/:/g" -e "s/[][ -]//g"
}

function get_optional {
    local OPT_DESC=
    echo ${OPT_DESC} | sed -e "s/[^[]*\(\[[^]]*\]\)[^[]*//g" -e "s/\([a-zA-Z]\) [A-Z_]\+/:/g" -e "s/[][ -]//g"
}

function get_required {
    local OPT_DESC=
    echo ${OPT_DESC} | sed -e "s/\([a-zA-Z]\) [A-Z_]\+/:/g" -e "s/\[[^[]*\]//g" -e "s/[][ -]//g"
}

function usage {
    printf "Usage:\n\t%s\n" "
#!/bin/bash
#
# [ and ] defines optional arguments
#

# location to getopts.sh file
source ./getopt.sh
USAGE="-u USER -d DATABASE -p PASS -s SID [ -a START_DATE_TIME ]"
parse_options "${USAGE}" ${@}

echo ${USER}
echo ${START_DATE_TIME}
${OPT_DESC}" exit 10 }

Running this script file:

运行这个脚本文件:

#!/bin/bash
# Option Description:
# -------------------
#
# Option description is based on getopts bash builtin. The description adds a variable name feature to be used
# on future checks for required or optional values.
# The option description adds "=>VARIABLE_NAME" string. Variable name should be UPPERCASE. Valid characters
# are [A-Z_]*.
#
# A option description example:
#   OPT_DESC="a:=>A_VARIABLE|b:=>B_VARIABLE|c=>C_VARIABLE"
#
# -a option will require a value (the colon means that) and should be saved in variable A_VARIABLE.
# "|" is used to separate options description.
# -b option rule applies the same as -a.
# -c option doesn't require a value (the colon absense means that) and its existence should be set in C_VARIABLE
#
#   ~$ echo get_options ${OPT_DESC}
#   a:b:c
#   ~$
#


# Required options 
REQUIRED_DESC="a:=>REQ_A_VAR_VALUE|B:=>REQ_B_VAR_VALUE|c=>REQ_C_VAR_FLAG"

# Optional options (duh)
OPTIONAL_DESC="P:=>OPT_P_VAR_VALUE|r=>OPT_R_VAR_FLAG"

function usage {
    IFS="|"
    printf "%s" 
# Example:
# parseArguments "${@}"
# echo "${ARG_0}" -> package
# echo "${ARG_1}" -> install
# echo "${ARG_PACKAGE}" -> "name with space"
# echo "${ARG_BUILD}" -> 1 (true)
# echo "${ARG_ARCHIVE}" -> 1 (true)
function parseArguments() {
  PREVIOUS_ITEM=''
  COUNT=0
  for CURRENT_ITEM in "${@}"
  do
    if [[ ${CURRENT_ITEM} == "--"* ]]; then
      printf -v "ARG_$(formatArgument "${CURRENT_ITEM}")" "%s" "1" # could set this to empty string and check with [ -z "${ARG_ITEM-x}" ] if it's set, but empty.
    else
      if [[ $PREVIOUS_ITEM == "--"* ]]; then
        printf -v "ARG_$(formatArgument "${PREVIOUS_ITEM}")" "%s" "${CURRENT_ITEM}"
      else
        printf -v "ARG_${COUNT}" "%s" "${CURRENT_ITEM}"
      fi
    fi

    PREVIOUS_ITEM="${CURRENT_ITEM}"
    (( COUNT++ ))
  done
}

# Format argument.
function formatArgument() {
  ARGUMENT="${1^^}" # Capitalize.
  ARGUMENT="${ARGUMENT/--/}" # Remove "--".
  ARGUMENT="${ARGUMENT//-/_}" # Replace "-" with "_".
  echo "${ARGUMENT}"
}
for i in ${REQUIRED_DESC}; do VARNAME=$(echo $i | sed -e "s/.*=>//g") printf " %s" "-${i:0:1} $VARNAME" done for i in ${OPTIONAL_DESC}; do VARNAME=$(echo $i | sed -e "s/.*=>//g") printf " %s" "[-${i:0:1} $VARNAME]" done printf "\n" unset IFS exit } # Auxiliary function that returns options characters to be passed # into 'getopts' from a option description. # Arguments: # : The options description (SEE TOP) # # Example: # OPT_DESC="h:=>H_VAR|f:=>F_VAR|P=>P_VAR|W=>W_VAR" # OPTIONS=$(get_options ${OPT_DESC}) # echo "${OPTIONS}" # # Output: # "h:f:PW" function get_options { echo | sed -e "s/\([a-zA-Z]\:\?\)=>[A-Z_]*|\?//g" } # Auxiliary function that returns all variable names separated by '|' # Arguments: # : The options description (SEE TOP) # # Example: # OPT_DESC="h:=>H_VAR|f:=>F_VAR|P=>P_VAR|W=>W_VAR" # VARNAMES=$(get_values ${OPT_DESC}) # echo "${VARNAMES}" # # Output: # "H_VAR|F_VAR|P_VAR|W_VAR" function get_variables { echo | sed -e "s/[a-zA-Z]\:\?=>\([^|]*\)//g" } # Auxiliary function that returns the variable name based on the # option passed by. # Arguments: # : The options description (SEE TOP) # : The option which the variable name wants to be retrieved # # Example: # OPT_DESC="h:=>H_VAR|f:=>F_VAR|P=>P_VAR|W=>W_VAR" # H_VAR=$(get_variable_name ${OPT_DESC} "h") # echo "${H_VAR}" # # Output: # "H_VAR" function get_variable_name { VAR=$(echo | sed -e "s/.*\:\?=>\([^|]*\).*//g") if [[ ${VAR} == ]]; then echo "" else echo ${VAR} fi } # Gets the required options from the required description REQUIRED=$(get_options ${REQUIRED_DESC}) # Gets the optional options (duh) from the optional description OPTIONAL=$(get_options ${OPTIONAL_DESC}) # or... $(get_options "${OPTIONAL_DESC}|${REQUIRED_DESC}") # The colon at starts instructs getopts to remain silent while getopts ":${REQUIRED}${OPTIONAL}" OPTION do [[ ${OPTION} == ":" ]] && usage VAR=$(get_variable_name "${REQUIRED_DESC}|${OPTIONAL_DESC}" ${OPTION}) [[ -n ${VAR} ]] && eval "$VAR=${OPTARG}" done shift $(($OPTIND - 1)) # Checks for required options. Report an error and exits if # required options are missing. # Using function version ... VARS=$(get_variables ${REQUIRED_DESC}) IFS="|" for VARNAME in $VARS; do [[ -v ${VARNAME} ]] || usage done unset IFS # ... or using IFS Version (no function) OLDIFS=${IFS} IFS="|" for i in ${REQUIRED_DESC}; do VARNAME=$(echo $i | sed -e "s/.*=>//g") [[ -v ${VARNAME} ]] || usage printf "%s %s %s\n" "-${i:0:1}" "${!VARNAME:=present}" "${VARNAME}" done IFS=${OLDIFS}

回答by Brian Cain

The example packaged with getopt(my distro put it in /usr/share/getopt/getopt-parse.bash) looks like it covers all of your cases:

打包的示例getopt(我的发行版放入/usr/share/getopt/getopt-parse.bash)看起来涵盖了您的所有情况:

##代码##

回答by Sebastian

I know that this is already answered, but for the record and for anyone with the same requeriments as me I decided to post this related answer. The code is flooded with comments to explain the code.

我知道这已经得到了回答,但是为了记录以及与我有相同要求的任何人,我决定发布此相关答案。代码中充斥着解释代码的注释。

Updated answer:

更新的答案:

Save the file as getopt.sh:

将文件另存为getopt.sh

##代码##

Then you can use it like this:

然后你可以像这样使用它:

##代码##

Old answer:

旧答案:

I recently needed to use a generic approach. I came across with this solution:

我最近需要使用通用方法。我遇到了这个解决方案:

##代码##

I didn't test this roughly, so I could have some bugs in there.

我没有粗略地测试这个,所以我可能有一些错误。

回答by Twoez

"getops" and "getopt" are very limited. While "getopt" is suggested not to be used at all, it does offer long options. Where as "getopts" does only allow single character options such as "-a" "-b". There are a few more disadvantages when using either one.

“getops”和“getopt”非常有限。虽然建议根本不要使用“getopt”,但它确实提供了很长的选项。“getopts”只允许单字符选项,例如“-a”“-b”。使用任何一种时还有一些缺点。

So i've written a small script that replaces "getopts" and "getopt". It's a start, it could probably be improved a lot.

所以我写了一个小脚本来代替“getopts”和“getopt”。这是一个开始,它可能会改进很多。

Update 08-04-2020: I've added support for hyphens e.g. "--package-name".

2020 年 8 月 4 日更新:我添加了对连字符的支持,例如“--package-name”。

Usage: "./script.sh package install --package "name with space" --build --archive"

用法:"./script.sh package install --package "name with space" --build --archive"

##代码##