Bash读取数组和Log msg shell脚本[重复]

dgtucam1  于 2023-05-07  发布在  Shell
关注(0)|答案(1)|浏览(181)

此问题已在此处有答案

Parsing JSON with Unix tools(47回答)
3天前关闭。
我是新的shell脚本,我试图记录与 curl 和grep命令的消息。
下面是curl命令

curl --cacert ds***ds*DS*ghgjhg**  > /data/result.out

这里运行curl命令并创建result.out文件。
下面是日志文件中的结果。
result.out

{
  "data": [
    {
      "numberOfRecords": 15,
      "objectType": "abc"
    },
    {
      "numberOfRecords": 10,
      "objectType": "pqr"
    },
    {
      "numberOfRecords": 32,
      "objectType": "xyz"
    }
  ],
  "errors": [
    {
      "errorMessage": "java.sql.SQLException:",
      "objectType": "xxx"
    }
  ]
}

我想检查是否有任何错误数组,并有errorMessage然后
log“curl命令失败..“+ errorMessage.
否则
日志“curl命令成功执行”
它试过了

if grep -w "errors" /data/result.out; then

echo "curl command failed." + errorMessage

else

echo "curl command succesfully executed"

exit 1

它检查错误字符串,但不知道如何检查是否有任何孩子,如果有,则获取errorMessage。试图找到解决方案,但无法找到任何适当的。

btqmn9zl

btqmn9zl1#

使用jq,正确的JSON解析器:

#!/bin/bash

curl --cacert ds***ds*DS*ghgjhg**  > file
err=$(jq -r '.errors | .[] | (.errorMessage + .objectType)' file)
if [[ $err && $err != null ]]; then
    echo >&2 "Error: $err"
    exit 1
else
    echo success
fi
$ apt-cache show jq
Package: jq
Version: 1.6-2.1ubuntu3
Section: utils
Installed-Size: 100
Depends: libjq1 (= 1.6-2.1ubuntu3), libc6 (>= 2.34)
Homepage: https://github.com/stedolan/jq
Description-en: lightweight and flexible command-line JSON processor
 jq is like sed for JSON data – you can use it to slice
 and filter and map and transform structured data with
 the same ease that sed, awk, grep and friends let you
 play with text.
 .
 It is written in portable C, and it has minimal runtime
 dependencies.
 .
 jq can mangle the data format that you have into the
 one that you want with very little effort, and the
 program to do so is often shorter and simpler than
 you’d expect

相关问题