Dylan Steward
Dylan Steward

Reputation: 31

jq: How do I assign a jq output to a variable?

I'm new to jq and struggling to obtain a json value and use it in a bash IF statement.

{
    "animal": "elephant",
    "colour": "red"
}
VAR=$( jq '.animal' animal.json )
echo "$VAR"

if [[ "$VAR" == "elephant" ]]; then
      echo "this is an elephant"
else
      echo "failed"
fi

When I run the script the comparison fails

What can change to make the script work?

Upvotes: 3

Views: 6585

Answers (1)

0stone0
0stone0

Reputation: 44274

jq outputs "elephant", note the "

Add -r to the jq command so the quotes are removed (raw-mode)


Then the output will match the string elephant

#!/bin/bash

VAR="$(jq -r '.animal' animal.json)"
echo "$VAR"

if [[ "$VAR" == "elephant" ]]; then
      echo "this is an elephant"
else
      echo "failed"
fi

Upvotes: 7

Related Questions