如何在传递的sh var中使用空格处理多个参数?

时间:2018-07-21 19:36:15

标签: printf sh posix

我有一个运行另一个命令的posix sh脚本。第二个命令可以传递零个,一个或多个选项。这些选项作为环境变量传递,例如$OPTIONS。但是,某些选项中可以有空格。

例如如果我执行的命令是curl,那么我的选择是CURL_OPTIONS

#!/bin/sh
# do some processing
curl $CURL_OPTIONS https://some.example.com

只要CURL_OPTIONS都不包含空格,我就可以了,例如

CURL_OPTIONS="--user me:pass --user-agent foo"

但是,如果选项包含空格,则sh会将其扩展并像对待自己的var一样对待它们:

CURL_OPTIONS="--header 'Authorization: token abcdefg'"

可以运行curl --header 'Authorization: token abcdefg' https://some.url.com,因为sh会解释单引号'并将Authorization: token abcdefg作为单个参数传递给curl,一切都很好。

但是,由于我正在使用var,因此sh会在看到$CURL_OPTIONS后将其扩展,并且不会将单引号Authorization: token abcdefg解释为单个参数。上面的结果是:

curl: (6) Could not resolve host: token
curl: (6) Could not resolve host: abcdefg'

(请注意,它甚至会将单引号视为abcdefg'的一部分。)

是的,我见过this question and its answers,但在这种情况下似乎都不起作用。

更新:

哦,现在这很有趣https://stackoverflow.com/a/31485948/736714 为什么我没有想到xargs

1 个答案:

答案 0 :(得分:2)

实际上,这可行。

CURL_OPTIONS=(--header "Authorization: token abcdefg")
curl "${CURL_OPTIONS[@]}" www.example.com

How to pass quoted arguments from variable to bash script

更新: 我猜这个下一个代码段应该符合POSIX(尽管有点逃脱)

CURL_OPTIONS="--header \\\"Authorization:\ token\ abcdefg\\\""
eval set -- $CURL_OPTIONS
curl "$@" www.example.com
相关问题