如何在 shell 中解析长格式参数?

发布于 2025-01-04 21:21:37 字数 134 浏览 1 评论 0原文

我看到的所有内容都使用 getopt 或稍微花哨的 getopts ,它只支持单字符选项(例如 -h 但不支持 - -帮助)。我想做一些花哨的长选择。

Everything I see uses getopt or the slightly-fancier getopts which only supports one-character options (e.g., -h but not --help). I want to do fancy long options.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

ㄟ。诗瑗 2025-01-11 21:21:37

我做了类似的事情这个

_setArgs(){
  while [ "${1:-}" != '' ]; do
    case "$1" in
      '-c' | '--configFile')
        shift
        configFile=$1
        ;;
      '-f' | '--forceUpdate')
        forceUpdate=true
        ;;
      '-r' | '--forceRetry')
        forceRetry=true
        ;;
    esac
    shift
  done
}

正如您所看到的,这很好地支持单字符和较长的选项。它允许将值与每个参数关联,如 --configFile 的情况。它也具有相当的可扩展性,对于可以配置哪些选项等没有人为限制。

如上所述,"${1:-}" 可以防止在 bash 中运行时出现“未绑定变量”错误“严格”模式(set -euo pipelinefail)。

I've done something like this:

_setArgs(){
  while [ "${1:-}" != '' ]; do
    case "$1" in
      '-c' | '--configFile')
        shift
        configFile=$1
        ;;
      '-f' | '--forceUpdate')
        forceUpdate=true
        ;;
      '-r' | '--forceRetry')
        forceRetry=true
        ;;
    esac
    shift
  done
}

As you can see, this supports both the single-character and the longer options nicely. It allows for values to be associated with each argument, as in the case of --configFile. It's also quite extensible, with no artificial limitations as to what options can be configured, etc.

As included above, the "${1:-}" prevents an "unbound variable" error when running in bash "strict" mode (set -euo pipefail).

旧情别恋 2025-01-11 21:21:37

假设您“想要做一些奇特的长选项”,而不管使用什么工具,只需使用 getoptgetopts 似乎主要在可移植性至关重要时使用)。这是关于最大复杂度的示例你会得到:

params="$(getopt -o e:hv -l exclude:,help,verbose --name "$(basename "$0")" -- "$@")"

if [ $? -ne 0 ]
then
    usage
fi

eval set -- "$params"
unset params

while true
do
    case $1 in
        -e|--exclude)
            excludes+=("$2")
            shift 2
            ;;
        -h|--help)
            usage
            ;;
        -v|--verbose)
            verbose='--verbose'
            shift
            ;;
        --)
            shift
            break
            ;;
        *)
            usage
            ;;
    esac
done

使用此代码,你可以指定-e/--exclude 多次,并且 ${excludes[@]} 将包含所有给定的排除项。处理后(-- 始终存在),剩余的任何内容都存储在 $@ 中。

Assuming that you "want to do fancy long options" regardless of the tool, just go with getopt (getopts seems to be mainly used when portability is crucial). Here's an example of about the maximum complexity that you'll get:

params="$(getopt -o e:hv -l exclude:,help,verbose --name "$(basename "$0")" -- "$@")"

if [ $? -ne 0 ]
then
    usage
fi

eval set -- "$params"
unset params

while true
do
    case $1 in
        -e|--exclude)
            excludes+=("$2")
            shift 2
            ;;
        -h|--help)
            usage
            ;;
        -v|--verbose)
            verbose='--verbose'
            shift
            ;;
        --)
            shift
            break
            ;;
        *)
            usage
            ;;
    esac
done

With this code, you can specify -e/--exclude more than once, and ${excludes[@]} will contain all of the given excludes. After processing (-- is always present) anything remaining is stored in $@.

ぃ双果 2025-01-11 21:21:37

我创建了一个最容易使用且无需自定义的 bash 函数。只需使用该函数并传递所有带或不带参数的长选项,该函数会将它们设置为变量,并将相应的选项参数作为脚本中的值。

function get_longOpt {
  ## Pass all the script's long options to this function.
  ## It will parse all long options with its arguments,
  ## will convert the option name to a variable and
  ## convert its option value to the variable's value.
  ## If the option does not have an argument, the
  ## resulting variable's value will be set to true.
  ## Works properly when providing long options, only.
  ## Arguments to options may not start with two dashes.
  ##
  ####  Usage
  ##
  ## get_longOpt $@
  ##
  ##  May expand to:
  ##
  ## get_longOpt --myOption optimopti --longNumber 1000 --enableMe --hexNumber 0x16
  ##
  ### Results in the bash interpretation of:
  ## myOption=optimopti
  ## longNumber=1000
  ## enableMe=true
  ## hexNumber=0x16
  ##
  local -a opt_list=( $@ )
  local -A opt_map
  local -i index=0
  local next_item
  for item in ${opt_list[@]}; do
    # Convert arg list to map.
    let index++
    next_item="${opt_list[$index]}"
    if   [[ "${item}" == --* ]] \
      && [[ "${next_item}" != --* ]] \
      && [[ ! -z "${next_item}" ]]
    then
      item="$(printf '%s' "${item##*-}")"
      opt_map[${item}]="${next_item}"
    elif [[ "${item}" == --* ]] \
      && { [[ "${next_item}" == --* ]] \
      || [[ -z "${next_item}" ]]; }
    then
      item="$(printf '%s' "${item##*-}")"
      opt_map[${item}]=true
    fi
  done
  for item in ${!opt_map[@]}; do
    # Convert map keys to shell vars.
    value="${opt_map[$item]}"
    [[ ! -z "${value}" ]] && \
    printf -v "$item" '%s' "$value"
  done
}

最新的原始源代码可以在这里找到:

https://github .com/theAkito/akito-libbash/blob/master/bishy.bash

I have created a bash function that is the easiest to use and needs no customization. Just use the function and pass all long options with or without arguments and the function will set them as variables with the corresponding option arguments as values in your script.

function get_longOpt {
  ## Pass all the script's long options to this function.
  ## It will parse all long options with its arguments,
  ## will convert the option name to a variable and
  ## convert its option value to the variable's value.
  ## If the option does not have an argument, the
  ## resulting variable's value will be set to true.
  ## Works properly when providing long options, only.
  ## Arguments to options may not start with two dashes.
  ##
  ####  Usage
  ##
  ## get_longOpt $@
  ##
  ##  May expand to:
  ##
  ## get_longOpt --myOption optimopti --longNumber 1000 --enableMe --hexNumber 0x16
  ##
  ### Results in the bash interpretation of:
  ## myOption=optimopti
  ## longNumber=1000
  ## enableMe=true
  ## hexNumber=0x16
  ##
  local -a opt_list=( $@ )
  local -A opt_map
  local -i index=0
  local next_item
  for item in ${opt_list[@]}; do
    # Convert arg list to map.
    let index++
    next_item="${opt_list[$index]}"
    if   [[ "${item}" == --* ]] \
      && [[ "${next_item}" != --* ]] \
      && [[ ! -z "${next_item}" ]]
    then
      item="$(printf '%s' "${item##*-}")"
      opt_map[${item}]="${next_item}"
    elif [[ "${item}" == --* ]] \
      && { [[ "${next_item}" == --* ]] \
      || [[ -z "${next_item}" ]]; }
    then
      item="$(printf '%s' "${item##*-}")"
      opt_map[${item}]=true
    fi
  done
  for item in ${!opt_map[@]}; do
    # Convert map keys to shell vars.
    value="${opt_map[$item]}"
    [[ ! -z "${value}" ]] && \
    printf -v "$item" '%s' "$value"
  done
}

The up to date original source code is available here:

https://github.com/theAkito/akito-libbash/blob/master/bishy.bash

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文