Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get field from json and assign to variable in bash script?

Tags:

I have a json store in jsonFile

{   "key1": "aaaa bbbbb",   "key2": "cccc ddddd" } 

I have code in mycode.sh:

#!/bin/bash value=($(jq -r '.key1' jsonFile)) echo "$value" 

After I run ./mycode.sh the result is aaaa but if I just run jq -r '.key1' jsonFile the result is aaaa bbbbb

Could anyone help me?

like image 308
user3441187 Avatar asked Mar 20 '14 09:03

user3441187


People also ask

Can you assign variables in bash?

A variable in bash can contain a number, a character, a string of characters. You have no need to declare a variable, just assigning a value to its reference will create it.

What is $@ in bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.

How do you declare a string variable in bash?

To initialize a string, you directly start with the name of the variable followed by the assignment operator(=) and the actual value of the string enclosed in single or double quotes. Output: This simple example initializes a string and prints the value using the “$” operator.


1 Answers

With that line of code

value=($(jq -r '.key1' jsonFile)) 

you are assigning both values to an array. Note the outer parantheses () around the command. Thus you can access the values individually or echo the content of the entire array.

$ echo "${value[@]}" aaaa bbbb  $ echo "${value[0]}" aaaa  $ echo "${value[1]}" bbbb 

Since you echoed $value without specifying which value you want to get you only get the first value of the array.

like image 115
Saucier Avatar answered Oct 05 '22 02:10

Saucier