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

时间:2016-06-13 07:38:10

标签: 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; shift;;
      -h) echo "$usage"; exit 0;;
      --) cmd="$2"; shift; break;;
     esac
   done

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

2 个答案:

答案 0 :(得分:1)

您应该在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 !

答案 1 :(得分:0)

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