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

标签 bash shell curl

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

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

但 bash 不会扩展 $1,因为 -d 后有单引号。谷歌按预期返回错误:

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

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

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

最佳答案

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

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

关于bash - 如何在单引号内扩展变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38014344/

相关文章:

php - 防止屏幕输出heredoc

shell - 使用nagios调用shell脚本执行

php/curl - 使用 header 获取远程服务器上的图像扩展

linux - 如何从变量运行脚本命令?

linux - 尝试使用 trap 跳出 shell 函数

json - 将 JSON 导出到环境变量

ruby - 在同一个 shell 进程中运行多个命令

linux - 编辑 : how to use gzip instead of tar

python - Flask 发布 JSON

json - 使用基本身份验证通过 CURL 发布 JSON