防止bash向变量输出添加单引号

时间:2017-09-22 23:57:31

标签: bash shell curl scripting

问题: 我正在编写一个脚本,使用curl执行多个HTTP请求,我想将标头添加到变量CURL_HEADERS,这样我就不必经常输入它们了。当我在curl命令中回显CURL_HEADERS变量时,单引号出现在我不想要它们的地方。我怎么能阻止这个? (为清楚起见,下面的代码是简化的)

代码

#!/usr/bin/env bash
AUTH_KEY='1234'
set -x
CURL_HEADERS='-H "Authorization: Basic '${AUTH_KEY}'" -H "Content-Type: application/json"'
echo "${CURL_HEADERS}"
curl -s $(echo "${CURL_HEADERS}") 'http://www.example.org' > /dev/null
set +x

预期输出:

+ CURL_HEADERS='-H "Authorization: Basic 1234" -H "Content-Type: application/json"'
+ echo '-H "Authorization: Basic 1234" -H "Content-Type: application/json"'
-H "Authorization: Basic 1234" -H "Content-Type: application/json"
++ echo '-H "Authorization: Basic 1234" -H "Content-Type: application/json"'
+ curl -s -H "Authorization: Basic 1234" -H "Content-Type: application/json" http://www.example.org
+ set +x

实际输出

+ CURL_HEADERS='-H "Authorization: Basic 1234" -H "Content-Type: application/json"'
+ echo '-H "Authorization: Basic 1234" -H "Content-Type: application/json"'
-H "Authorization: Basic 1234" -H "Content-Type: application/json"
++ echo '-H "Authorization: Basic 1234" -H "Content-Type: application/json"'
+ curl -s -H '"Authorization:' Basic '1234"' -H '"Content-Type:' 'application/json"' http://www.example.org
+ set +x

2 个答案:

答案 0 :(得分:8)

一个相当简单的解决方案是使用bash数组来存储您想要传递的四个参数:

CURL_HEADERS=(
             '-H' "Authorization: Basic ${AUTH_KEY}"
             '-H' 'Content-Type: application/json'
)

curl -s "${CURL_HEADERS[@]}" 'http://www.example.org' > /dev/null

与标量变量不同,标量变量只是普通字符的普通字符串,无论它们可能包含多少引号,数组都是字符串列表,每个字符串彼此区分一个。从这个意义上说,bash就像几乎所有其他编程语言一样。

这个问题以及我建议的解决方案以及其他几个解决方案在Bash FAQ条目50(I'm trying to put a command in a variable, but the complex cases always fail!)中有详细描述,值得详细阅读。 (链接取自@ John1024的评论。)

答案 1 :(得分:0)

建议的数组是一种很好的设计方法,但是curl仍然向已经在其周围包含双引号的数组项添加单引号,从而使标题无效。