使用 jq 解析 curl 输出并在 unix 中进行比较 shell

Parse curl output with jq and compare in unix shell

谁能帮我解决这个错误:

错误:


  ~> /bin/bash -c [[ $(curl -s  -H "Application: application/json" "https://jsonplaceholder.typicode.com/todos/1" | jq .'["userId"]' ) == "1"]]
1: -c: line 1: unexpected token `EOF' in conditional command
1: -c: line 1: syntax error: unexpected end of file

这是 API 输出:

  ~> curl -s  -H "Application: application/json" "https://jsonplaceholder.typicode.com/todos/1"
{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false

  ~> curl -s  -H "Application: application/json" "https://jsonplaceholder.typicode.com/todos/1" | jq .'["userId"]'
1

我正在尝试在 puppet Exec 中使用此 shell 命令。

更新:

/bin/bash -c 'test `curl -s  -H "Application: application/json" "https://jsonplaceholder.typicode.com/todos/1" | jq .'["userId"]'` == "1"'
jq: error: userId/0 is not defined at <top-level>, line 1:
.[userId]
jq: 1 compile error
(23) Failed writing body
/bin/bash: line 0: test: ==: unary operator expected

知道了:

/bin/bash -c "test `curl -s  -H \"Application: application/json\" \"https://jsonplaceholder.typicode.com/todos/1\" | jq .'[\"userId\"]'` == \"1\""

谢谢詹姆斯

这里的问题是 bash 语法不正确,而不是 curljq -- 当然这些也可能有问题,但首先要...错误原因:

  1. 由于-c选项,双括号需要单引号。

  2. 在右双括号 ]].

    之前需要 space

简单的例子;测试 5 是否等于 5:

没有单引号失败:

bash -c [[ 5 == 5 ]]

输出:

5: -c: line 1: unexpected token `EOF' in conditional command
5: -c: line 1: syntax error: unexpected end of file

]]失败之前没有space:

bash -c '[[ 5 == 5]]'

输出:

bash: -c: line 0: unexpected EOF while looking for `]]'
bash: -c: line 1: syntax error: unexpected end of file

成功:

bash -c '[[ 5 == 5 ]]'

将其应用于 OP 代码:

/bin/bash -c '[[ $(curl -s  -H "Application: application/json" "https://jsonplaceholder.typicode.com/todos/1" | jq .'["userId"]' ) == "1" ]]'