Getting error while parsing json with jq in shell script

I have json which looks like this

  "phx4fo": {
    "db_name": "phx4fo",
    "db_unique_name": "phx4fo",
    "db_crs_state": "OFFLINE",
    "db_sid_list": "phx4fo1,phx4fo2",
    "db_host_list": "epxa25-swlke1,epxa25-swlke2",
    "db_home": "/u02/app/oracle/product/12.1.0/dbhome_2"
  "phx68r": {
    "db_name": "phx68r",
    "db_unique_name": "phx68r",
    "db_crs_state": "OFFLINE",
    "db_sid_list": "phx68r1,phx68r2",
    "db_host_list": "epxa25-swlke1,epxa25-swlke2",
    "db_home": "/u02/app/oracle/product/"

In some cases, dbname is present and in some cases, it is not. Now, I want if dbname is not present then it should exit code without doing anything.My code is:-

IFS=, read -r -a SIDLIST <<<"$(jq -r ".\"$dbname\".db_sid_list" $CRSOUT)"
    for SIDVAL in $SIDLIST;do
        if [[ ! -z "$SIDVAL" ]];then
             CHECK_SID=$(ps -eawf|grep smon|grep ^oracle|grep -v grep|grep -v ASM|grep -v perl|cut -d"_" -f3| grep $ORA_DB_NAME | grep -w $SIDVAL )
             if [[ ! -z "$CHECK_SID" ]];then

But instead of exit it is proceeding further

1 answer

  • answered 2022-01-13 06:59 peak

    In the comment, you seem to indicate that there is one value of $dbname, so the following should help:

    jq -r --arg dbname "$dbname" '(.[$dbname] // empty) |.db_sid_list' "$CRSOUT"

    With your sample JSON, the above results in:


    Presumably you will want to split on the comma, which can be done within the same jq query, e.g. by modifying it to:

    (.[$dbname] // empty) | .db_sid_list/"," | .[]

    By the way, if you are going to use read -a, then you will need to understand shell arrays, and modify your shell script accordingly. I would suggest you break down your problem into small pieces that you can solve independently, so that it will be easier to construct a complete solution.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum