我正在尝试将变量中的参数传递给curl
,但失败。我打开set -x
以获得更多信息,我对在这里看到的所有单引号感到非常困惑。
curlopts="-ksS -H 'Content-Type:application/x-www-form-urlencoded'"
$ curl "$curlopts" https://localhost
+ curl '-ksS -H '\''Content-Type:application/x-www-form-urlencoded'\''' https://localhost
curl: option -ksS -H 'Content-Type:application/x-www-form-urlencoded': is unknown
curl: try 'curl --help' or 'curl --manual' for more information
它可以像curl $curlopts https://localhost
这样不带引号,但我认为使用不带引号的变量通常是不好的做法。
答案 0 :(得分:1)
此:
curlopts="-ksS -H 'Content-Type:application/x-www-form-urlencoded'"
将curlopts
设置为-ksS -H 'Content-Type:application/x-www-form-urlencoded'
。
在上面之后,这是
curl "$curlopts" https://localhost
等效于此:
curl "-ksS -H 'Content-Type:application/x-www-form-urlencoded'" https://localhost
表示它使用两个参数调用curl
:-ksS -H 'Content-Type:application/x-www-form-urlencoded'
和https://localhost
。
但是,当然,您想使用四个参数调用curl
:-ksS
,-H
,Content-Type:application/x-www-form-urlencoded
和https://localhost
。
为此,我建议使用数组:
curlopts=(-ksS -H Content-Type:application/x-www-form-urlencoded)
curl "${curlopts[@]}" https://localhost
"${arrayname[@]}"
语法神奇地扩展为数组的每个元素的分开双引号。
(注意:我删除了单引号,因为这里不需要单引号-Content-Type:application/x-www-form-urlencoded
中的所有字符都不需要引号-但如果它们使您感到更快乐,则可以放心地重新添加它们)