Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store value to variable in Shell script [duplicate]

Tags:

bash

shell

jq

"$emails" has the array of values, i want to parse the values from it, To do it, i am using the jq. if i do below command

echo "$emails" | ./jq '.total_rows'

i could get the value i.e 4, i want to store the returned results into some variable,

total_rows="$emails" | ./jq '.total_rows'

but total_rows has no value.

echo $total_rows

How do store the returned result into variable?

like image 313
Sivailango Avatar asked Apr 27 '26 06:04

Sivailango


1 Answers

You have to use the right quotation, like this:

total_rows=`echo "$emails" | ./jq '.total_rows'`

The `` will execute the command and give total_rows the value of it, so whatever would be the output of

echo "$emails" | ./jq '.total_rows'

will so be stored in total_rows.

As mentioned in the comments by Tom Fenech, it is better to use $() for command substitution. It provides a better readability. So what you can do is:

total_rows=$(echo "$emails" | ./jq '.total_rows')
like image 130
Nidhoegger Avatar answered Apr 28 '26 21:04

Nidhoegger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!