【问题标题】:Working with Bash and cURL使用 Bash 和 cURL
【发布时间】:2017-10-23 12:48:10
【问题描述】:

我在这里发布了a question 并得到了满足我需要的答案。

我有一个类似的问题,但我找不到答案,所以我问另一个:/

当我直接在终端中运行以下命令时,通过管道输入 jq 时会得到正确的响应。

curl GET "https://jsonplaceholder.typicode.com/posts/2" | jq '.body'

RESPONSE: "*est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla*"

但是,当我在可执行的 bash 脚本中运行相同的命令时,我没有看到任何响应?

result="$(curl GET https://jsonplaceholder.typicode.com/posts/2)" | jq '.body'
echo "$result"

回显的结果是一个空字符串。

有人能指出我正确的方向吗,并可能用双引号/单引号等突出一些细微差别?我假设我犯了语法错误?

谢谢

【问题讨论】:

  • 管道和jq也需要在子shell中...
  • 这不是细微差别,它显然是唯一可行的方法。查看$() 的作用以及管道的工作原理。

标签: json bash curl jq


【解决方案1】:

您应该在子shell 内处理jq 中的结果。

result=$(curl GET https://jsonplaceholder.typicode.com/posts/2 | jq '.body')
echo "$result"

@123 在评论中首次指出

【讨论】:

    【解决方案2】:

    您声明了变量:result 但从未使用它。

    【讨论】:

    • 更新了我的问题,我在附和它,只是忘了把它粘贴到问题中
    猜你喜欢
    • 1970-01-01
    • 2011-03-12
    • 2017-01-27
    • 1970-01-01
    • 2018-09-26
    • 2011-01-15
    • 1970-01-01
    • 2020-08-11
    • 2019-03-08
    相关资源
    最近更新 更多