getopt 不接受以连字符开头的参数值 -

getopt not accepting argument value starting with hyphen -

我的脚本有一个选项 o,它应该接受参数作为值,如下所示

./script -o '-p 2' ls

但是getopt不允许,报错

Unrecognized option '-p 2'

代码片段:

ARGS=$(getopt -a -n [=12=] -o o::h -- "$@")
   eval set -- "$ARGS"
   while true
   do
     case "" in
      -o) opt=""; echo "options: "; shift; shift;;
      -h) echo "$usage"; exit 0;;
      --) cmd=""; shift; break;;
     esac
   done

如何将参数作为值传递给脚本?

getopt 有问题且已过时,请尝试 getopts

您应该在 tutorial

之后使用 getopts
#!/bin/bash
while getopts "o:h" opt; do
   case $opt in
      o) option="$OPTARG"; echo "options: $option";;
      h) echo "$usage"; exit 0;;
   esac
done
cmd="${@: -1}" # Warning: Get the last argument, even if it doesn't exist !