1

is this correct?

    existed_design_document=$(curl "Administrator:*******@couchbase:8092/$MY_APP_DB_BUCKET/_design/dev_$environment" | jq '.error ')

    echo "$existed_design_document"
    if [ "$existed_design_document" == "not_found" ]
       then
         echo "The document design does not exist"
    fi

I see in the echo the value "not_found" but still I´m not getting into the if. Any idea why?

2
  • 2
    what's the output of declare -p existed_design_document or printf '%q\n' "$existed_design_document"? Like so you'll see if there are funny characters in your variable. echo is not reliable for this kind of inspections. Commented Oct 26, 2015 at 16:25
  • 1
    bash allows == inside [...], but it's good to get in the habit of using = instead (or use [[ ... == ... ]]). Commented Oct 26, 2015 at 16:34

2 Answers 2

2

When I try with this baby example:

$ a=$(echo '{"error": "not_found"}' | jq .error)

I get:

$ declare -p a
declare -- a="\"not_found\""

So the quotes are also in the output of jq. So you need this:

if [[ $existed_design_document = "\"not_found\"" ]]

As @EtanReisner points out (thanks!): jq has the -r flag:

       With  this  option, if the filter´s result is a string then it will
       be written directly to standard output rather than being  formatted
       as a JSON string with quotes. This can be useful for making jq fil‐
       ters talk to non-JSON-based systems.

So you should even do this:

existed_design_document=$(curl "Administrator:*******@couchbase:8092/$MY_APP_DB_BUCKET/_design/dev_$environment" | jq -r .error)
echo "$existed_design_document"
if [[ $existed_design_document = "not_found" ]; then
     echo "The document design does not exist"
fi
Sign up to request clarification or add additional context in comments.

2 Comments

The jq flag -r would also be useful here.
@EtanReisner Oh cool! (I didn't even read jq's man page, just answered from obvious facts… but will edit the answer).
0

One more reliable solution that is not affected by quotes, but only looks for a given string is based on regex. This will match your text:

if [[ $existed_design_document =~ not_found ]]; then
     echo "The document design does not exist"
fi

That will match anything that contain not_found, so, it is more flexible, but also could match some UN-expected strings. It is a trade-off between flexibility and precision.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.