-1

I am new to shell script and I am trying to log the message with curl and grep command.

following is curl command

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

Here this curl command run and create result.out file.

And following is the result in log file.

result.out

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

I want check if there are any errors array and have errorMessage then

log "curl command failed.. " + errorMessage.

else

log "curl command succesfully executed"

It tried.

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

echo "curl command failed." + errorMessage

else

echo "curl command succesfully executed"

exit 1

It checks for errors string but, not sure how to check if there are any child and if yes then fetching errorMessage. Tried to find solution but, couldn't find any proper.

ketan
  • 19,129
  • 42
  • 60
  • 98
  • 1
    Ideally, you should use something like `jq` to read the file. It will give you pretty precise control over what you look for. – Paul Hodges May 03 '23 at 15:48

1 Answers1

2

With jq, a proper JSON parser:

#!/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
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
  • 1
    it says: line 77: jq: command not found. I Did err=$(jq -r '.errors | .[] | (.errorMessage + .objectType)' /tmp/console.out) if [[ $err && $err != null ]]; then echo >&2 "Curl command failed: $err" – ketan May 03 '23 at 16:23
  • Yes, you need to install `jq`, see link in my answer. ` – Gilles Quénot May 03 '23 at 16:38