【问题标题】:getopt not accepting argument value starting with hyphen -getopt 不接受以连字符开头的参数值 -
【发布时间】:2016-06-13 07:38:10
【问题描述】:

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

./script -o '-p 2' ls

但是getopt不允许,报错

Unrecognized option '-p 2'

代码sn-p:

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

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

【问题讨论】:

  • edit您的问题并包括您脚本的相关部分。
  • 试试./script -o -- '-p 2'?
  • 虽然没有报错,但无法将值放入opt变量

标签: bash getopt


【解决方案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 !

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-12
      • 2021-10-16
      • 2021-10-07
      • 2018-02-15
      相关资源
      最近更新 更多