PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, December 15, 2022

[FIXED] How to assign the result of an expression to a variable in bash

 December 15, 2022     bash, syntax, variable-assignment     No comments   

Issue

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?


Solution

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'
)


Answered By - KamilCuk
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing