Topper
Topper

Reputation: 500

How can manage jq return boolean value to bash for future proceed

I have to proceed output from app which produce JSON output. Must check "code" filed if it's different from 0 to make some actions. Decide to done it in Bash script but now I can't find a way (jq totally noob) to return boolean false or exit 0 to next switch case.

That's what I've tried:

app | jq -r 'if (.code != 0 ) then (@sh 'exit 1') else empty end'
app | jq -r 'if (.code != 0 ) then (boolean (false)) else empty end'

but all time errors like:

jq: error: syntax error, unexpected INVALID_CHARACTER (Unix shell quoting issues?) at <top-level>, line 1:
if (.code != 0 ) then (@sh 'exit 1') else empty end                           
jq: 1 compile error
exit status 3

That's the input JSON

And the output is extensive (that's not complete output)

{
  "code" : 0,
  "description" : "Success",
  "response" : {
    "properties" : [
        {
            "name" : "name",
            "value" : "\"cam_src_pipe\"",
            "param" : {
                "description" : "The name of the current Gstd session",
                "type" : "gchararray",
                "access" : "((GstdParamFlags) READ | 234)"
            }
        },
        {
            "name" : "description",
            "value" : "\"imxv4l2videosrc imx-capture-mode=0 ! imxipuvideotransform deinterlace=true ! interpipesink name=cam_src caps=video/x-raw,width=640,height=480,framerate=30/1 sync=true async=false forw
ard-eos=true\"",
            "param" : {
                "description" : "The gst-launch like pipeline description",
                "type" : "gchararray",
                "access" : "((GstdParamFlags) READ | 234)"
            }
        },
        {
            "name" : "elements",
            "value" : "((GstdList*) 0x560c63a0)",
            "param" : {
                "description" : "The elements in the pipeline",
                "type" : "GstdList",
                "access" : "((GstdParamFlags) READ | 224)"
            }
        },

I have to get boolean false or exit 1 to proceed with Bash

Upvotes: 2

Views: 3006

Answers (2)

Cavaz
Cavaz

Reputation: 3119

you can leverage the -e option, that sets the exit status of jq based on the query:

echo '{"code": 1}' | jq -e '.code == 0'
echo $?      # prints 1

You can use it to exit by checking the status explicitly

app | jq -e '.code == 0' || exit 1

# or

app | jq -e '.code == 0'
if [ $? -eq 1 ] ; then
  exit 1
fi

Upvotes: 1

nullPointer
nullPointer

Reputation: 4574

I'm not a jq expert, but can't you use something like the below ? You can store into a variable what you parse with jq, and proceed as needed.

code=$(app | jq '.code')
if [ $code -eq 0 ]  
  then ...
  else ...
fi

Upvotes: 2

Related Questions