Issue
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.
Solution
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
Answered By - Gilles Quénot Answer Checked By - Willingham (WPSolving Volunteer)