简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM