Home > database >  How to assign the result of an expression to a variable in bash
How to assign the result of an expression to a variable in bash

Time:06-16

In following bash script I'm trying to assign a value from a json object to a variable.

#!/bin/bash

json_data='{"ip":"1.2.3.4", "country_code":"GB", "country_name":"United Kingdom"}'

echo json_data:
echo $json_data

echo country_code:
echo $json_data | jq '.country_code'

echo country_name:
echo $json_data | jq '.country_name'

cc=$json_data | jq '.country_code'

echo cc:
echo $cc

cn=$($json_data | jq '.country_name')

echo cn:
echo $cn

Just echoing the expressions works. Assigning the value of the expressions to variables cc or cn doesn't.

$ ./test.sh 
json_data:
{"ip":"1.2.3.4", "country_code":"GB", "country_name":"United Kingdom"}
country_code:
"GB"
country_name:
"United Kingdom"
cc:

./test.sh: line 19: {"ip":"1.2.3.4",: command not found
cn:

$

I thought that wrapping an expression in $(...) gave the functionality I need, but that results in an error.

Could anyone advise as to the correct syntax?

CodePudding user response:

I thought that wrapping an expression in $(...) gave the functionality

You did not wrap enough. Wrap the whole expression, including echo.

cn=$(echo "$json_data" | jq '.country_name')

Remember to quote variable expansions. Check your script with shellcheck - shellcheck will notify you of many problems.

You can put anything inside $(...), maybe this will clear it:

cn=$(
  echo "$json_data" | jq '.country_name'
)
  • Related