Shell variables with pipes

Viewed 34

I make a get request to a public API via the unix shell. Then I select a specific string value pair. This works perfectly, however I am unable to assign it to a variable called max_temperature.

Can someone help?

 response="$(curl $url)"
 max_temperature=$response |  jq '.["main"].temp_max'
1 Answers

The line

 max_temperature=$response |  jq '.["main"].temp_max'

will cause the max_temparature var to be set to the contents of $response and pipe the output of this statement (in this case no output) to jq.

What you probably want is:

max_temperature=$(echo $response | jq '.["main"].temp_max')

This spawns a subshell and executes

echo $response | jq '.["main"].temp_max'

in it.

However, since a subshell does not take its parents environment with it by default, $response will be empty when it is echoed. You will need to export it in the line before. Hence:

 response="$(curl $url)"
 export response 
 max_temperature=$(echo $response |  jq '.["main"].temp_max')

More on Command substitution

Related