bash getopts 使用 option/flag 作为参数

bash getopts uses option/flag as argument

我正在编写一个 bash shell 脚本,它可以使用标志 -l -u-w [argument]

我有以下(简化的)代码:

while getopts ":ulw:" arg; do
    case "$arg" in
    u)
        U=1
        ;;
    l)
        L=1
        ;;

    w)
        W=1
        VALUE="${OPTARG}"
        ;;

    esac
done

当我 运行 使用 -w42 -l 我的脚本时,它可以正常工作。如果我使用 -lw42 它也有效,但是当我使用 -w42l 时,它认为 42l 是参数(而不仅仅是 42)并且它使 VALUE variable = 42l 并忽略 -l 选项。

如何让脚本同时适用于 -w42 -l-lw42-w42l

编辑:澄清一下,我知道这不是它应该的工作方式,但我的大学要求我以这种方式工作

关于标准合规性

你正在尝试的东西本来就不应该起作用。

POSIX utility syntax 准则 #5 指出:

One or more options without option-arguments, followed by at most one option that takes an option-argument, should be accepted when grouped behind one '-' delimiter.

因此,采用选项参数的选项(在本例中为 -w)只允许成为由单个 [ 启动的组中的 last 一个=12=].


无论如何让它发挥作用

如果不能处理符合标准的行为,就不能使用getopts,所以需要自己写逻辑。一种方法可能如下所示:

#!/usr/bin/env bash
#              ^^^^- note bash, not sh; the below code uses non-POSIX extensions

while (( $# )) && [[  = -* ]]; do
  arg=${1#-}; shift
  while [[ $arg ]]; do
    case $arg in
      l*) flag_l=1; arg=${arg#l};;
      u*) flag_u=1; arg=${arg#u};;
      w*)
        flag_w=1
        rest=${arg#w}
        if [[ -z $rest ]]; then
          arg=; shift; rest=$arg
        fi
        if [[ $rest =~ ^([[:digit:]]+)(.*) ]]; then
          w_value=${BASH_REMATCH[1]}
          arg=${BASH_REMATCH[2]}
        else
          echo "ERROR: -w not followed with a number" >&2
          exit 1
        fi
        ;;
      *) echo "Unrecognized flag: $arg" >&2; exit 1;;
    esac
  done
done

echo "After parsing:"
echo "flag_w = ${flag_w:-0}"
echo "flag_l = ${flag_l:-0}"
echo "flag_u = ${flag_u:-0}"
echo "w_value = ${w_value:-0}"

https://ideone.com/eDrlHd

的在线解释器中查看此 运行