Home > Mobile >  Is there way, to use bash variable stored in json?
Is there way, to use bash variable stored in json?

Time:04-28

I've got two simple files, bash script and json file:

{
  "age": "22",
  "message": "You are ${age} years old"
}
age=$(jq -r .age file.json)
message=$(jq -r .message file.json)
echo ${message}

When echoing message, as output I've got

You are ${age} years old

not

You are 22 years old

Is there some way in this scenario, to replace ${age} with variable (for bash to know, that there's variable in there, not just plain string)? I could probably use sed, to manually replace it, but that's not what I'm asking about.

CodePudding user response:

You can use envsubst to replace the string ${stuff} for exported variables.

age="$age" envsubst <<<"${message}"

CodePudding user response:

You can do with a single call to jq :

jq -r '.age as $age|.message|sub("\\${age}";$age)' input.json
  • Related