Lorccan
Lorccan

Reputation: 823

Null test in bash

This returns null:

jq --arg light "$i" '.lightstates[$light].on' "$tmp_dir/evening_brightness.json"

However, when I test for null, I get an unexpected result:

[[ -z $(jq --arg light "$i" '.lightstates[$light].on' "$tmp_dir/evening_brightness.json") ]] && echo "null" || echo "not null"
not null

I have tried variations - using -n and testing for an empty string - but neither of these gives the result I want over a range of value (where I want to not echo anything where there's no useful value in a variable).

(Potential values are: true, false, string, null.)

Upvotes: 0

Views: 50

Answers (2)

chepner
chepner

Reputation: 530990

jq is outputting the literal string null. However, you can add the -e flag to json so that its exit status is non-zero when it produces a null or false value.

if jq -e --arg light "$i" '.lightstates[$light].on' "$tmp_dir/evening_brightness.json" > /dev/null; then
  echo "not null"
else
  echo "null"
fi

Upvotes: 1

Chris Maes
Chris Maes

Reputation: 37722

bash does not know a null value. You need to compare strings in this case:

[ "$(jq -c '.abc' <<< "{}")" == "null" ] && echo "is null"

alternatively you can use the --exit-status option from jq:

-e / --exit-status:

Sets the exit status of jq to 0 if the last output values was neither false nor null, 1 if the last output value was either > false or null, or 4 if no valid result was ever produced. Normally jq exits with 2 if there was any usage problem or system error, 3 if there was a jq program compile error, or 0 if the jq program ran.

Upvotes: 2

Related Questions