在bash中将getopts样式args组合在一起

时间:2017-10-20 01:43:23

标签: bash getopt getopts

我希望能够在bash中存储一堆args,我想在一堆不同的curl命令中使用它们。但是,到目前为止,我的尝试还没有在参数中包含空格的情况下起作用。

我制作了一个简单的bash脚本来复制问题,getopts.sh

#!/bin/bash

while getopts ":a:b:c:" opt; do
  case $opt in
    a)
      echo "-a was triggered, Parameter: $OPTARG" >&2
      ;;
    b)
      echo "-b was triggered, Parameter: $OPTARG" >&2
      ;;
    c)
      echo "-c was triggered, Parameter: $OPTARG" >&2
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires an argument." >&2
      exit 1
      ;;
  esac
done

我想得到的最终结果是能够以下列方式调用此脚本,并按预期工作:

OPTS="-a foo -b bar -c baz"
./getopts.sh $OPTS -d foo
./getopts.sh $OPTS -e bar

我用几种不同的方式称呼它:

[julius@julius getopts]$ OPTS="-a foo -b bar -c baz"
[julius@julius getopts]$ ./getopts.sh $OPTS
-a was triggered, Parameter: foo
-b was triggered, Parameter: bar
-c was triggered, Parameter: baz

第一个按预期工作,然而,事情快速向南:

[julius@julius getopts]$ OPTS="-a foo -b bar -c \"aaa bbb\""
[julius@julius getopts]$ ./getopts.sh $OPTS
-a was triggered, Parameter: foo
-b was triggered, Parameter: bar
-c was triggered, Parameter: "aaa

我希望c参数为aaa bbb,但我得"aaa 逃离这个空间并没有帮助:

[julius@julius getopts]$ OPTS="-a foo -b bar -c aaa\ bbb"
[julius@julius getopts]$ ./getopts.sh $OPTS
-a was triggered, Parameter: foo
-b was triggered, Parameter: bar
-c was triggered, Parameter: aaa\

Heredoc是一样的:

[julius@julius getopts]$ read -d '' OPTS << EOF
> -a foo
> -b bar
> -c "aaa bbb"
> EOF
[julius@julius getopts]$ ./getopts.sh $OPTS
-a was triggered, Parameter: foo
-b was triggered, Parameter: bar
-c was triggered, Parameter: "aaa

有没有办法在变量中一起指定一堆getopt选项以便在bash中重用?为什么不做上述工作?

0 个答案:

没有答案