【问题标题】:Pass parameters as option in custom getopts script in bash在 bash 中的自定义 getopts 脚本中将参数作为选项传递
【发布时间】:2015-09-05 10:16:27
【问题描述】:

我想将选项作为参数传递。例如:

mycommand -a 1 -t '-q -w 111'

脚本无法识别引号中的字符串。即它只获取字符串的一部分。

getopts 的工作原理相同 - 它只能看到 -q

对于自定义 getopts,我使用类似的脚本(示例):

while :
do
    case $1 in
        -h | --help | -\?)
            # Show some help
            ;;
        -p | --project)
            PROJECT="$2"
            shift 2
            ;;
        -*)
            printf >&2 'WARN: Unknown option (ignored): %s\n' "$1"
            shift
            ;;
        *)  # no more options. Stop while loop
            break
            ;;
        --) # End of all options
        echo "End of all options"
            shift
            break
            ;;
    esac
done

【问题讨论】:

  • 您希望脚本如何使用'-q -w 111'?和不引用一样吗?
  • 我使用调用另一个脚本。 anotherscript $customOptions
  • getopts解析部分中没有-t...?
  • @chepner 你可以在开始时使用set - $@
  • 你真的不想使用未引用的$@;您会丢失有关哪些参数可能包含空格的信息。

标签: bash getopt getopts


【解决方案1】:

也许我误解了这个问题,但getopts 似乎对我有用:

while getopts a:t: arg
do
    case $arg in
        a)  echo "option a, argument <$OPTARG>"
            ;;
        t)  echo "option t, argument <$OPTARG>"
            ;;
    esac
done

运行:

bash gash.sh -a 1 -t '-q -w 111'
option a, argument <1>
option t, argument <-q -w 111>

这不是你想要的吗?也许您在带参数的选项之后错过了:

【讨论】:

  • 嗯,我通过类似的方式检查了它,但没有工作。我会检查你的例子。谢谢!
  • 您的脚本运行良好。似乎我在某个地方犯了错误,它对我不起作用。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-16
  • 2021-06-09
  • 1970-01-01
相关资源
最近更新 更多