我希望能够在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中重用?为什么不做上述工作?