如何在单引号内扩展变量?

时间:2016-06-24 13:13:55

标签: bash shell curl

我想运行这个简单的bash脚本:

  curl https://www.googleapis.com/urlshortener/v1/url?key=MyKey -H \\
  'Content-Type: application/json' -d '{"longUrl": "$1"}'

但由于$1之后的单引号,bash不会展开-d。谷歌预计将返回错误:

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "invalid",
    "message": "Invalid Value",
    "locationType": "parameter",
    "location": "resource.longUrl"
   }
  ],
  "code": 400,
  "message": "Invalid Value"
 }
}

如何展开$1-d发送的json对象的单引号内的curl

这个问题似乎确实重复,但我无法从其他问题中找出答案。我提供的脚本希望它对其他人有用。作为贡献。

3 个答案:

答案 0 :(得分:3)

您可以使用双引号,转义JSON字符串中的引号:

curl https://www.googleapis.com/urlshortener/v1/url?key=MyKey -H \\
  'Content-Type: application/json' -d "{\"longUrl\": \"$1\"}"

答案 1 :(得分:2)

单引号中不会发生

Parameter expansion,您需要使用双引号扩展:

curl https://www.googleapis.com/urlshortener/v1/url?key=MyKey -H \
  'Content-Type: application/json' -d '{"longUrl": "'"$1"'"}'

上面使用了字符串连接,下面每个都显示在一个单独的行上以便可见性:

'{"longUrl":"'
"$1"
'"}'

但是,如果$1包含双引号,您应该知道上述内容会中断,因为JSON无效。

答案 2 :(得分:1)

您还可以从here文档中读取数据,从而消除一层引号:

curl https://www.googleapis.com/urlshortener/v1/url?key=MyKey -H \\
'Content-Type: application/json' -d@- <<DATA
{"longUrl": "$1"}
DATA

即使这样,如果$1包含双引号,您仍可能会遇到问题。最安全的选择是使用jq之类的东西为你生成JSON。

jq -n --arg url "$1" '{longURL: $url}' | curl \
  https://www.googleapis.com/urlshortener/v1/url?key=MyKey \
  -H 'Content-Type: application/json' -d@-