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

Bash getopt不接受以连字符开头的参数值-,bash,getopt,Bash,Getopt,我的脚本有一个选项o,它应该接受参数作为值,如下所示 ./script -o '-p 2' ls 但是getopt不允许,给出了一个错误 Unrecognized option '-p 2' 代码段: ARGS=$(getopt -a -n $0 -o o::h -- "$@") eval set -- "$ARGS" while true do case "$1" in -o) opt="$2"; echo "options: $2"; shift;

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

./script -o '-p 2' ls
但是getopt不允许,给出了一个错误

Unrecognized option '-p 2'
代码段:

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

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

getopt有缺陷且过时,请尝试
getopts

您应该在


请回答您的问题并包括脚本的相关部分。请尝试
/script-o--'-p2'
?尽管它没有给出错误,但无法将值输入到
opt
变量中
#!/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 !