8

I'm using curl to get JSON back from a rest api like this:

content=$(curl -s  -X GET -H "Header:Value" http://127.0.0.1:8200/etc)
echo "${content}"| jq -r '.data.value'

which produces the value I need. However; when I change the above code to look like this:

content=$(curl -s  -X GET -H "Header:Value" http://127.0.0.1:8200/etc)
username=$(echo "${content}"| jq -r '.data.value')
echo $username

Produces nothing. How can I change this so that the username variable gets assigned the output?

10

Changed the code to this and it worked:

content=$(curl -s  -X GET -H "Header:Value" http://127.0.0.1:8200/etc) 
username=$( echo jq -r  '.data.value' <<< "${content}" ) 
echo ${username}
  • 1
    I get Syntax error: redirection unexpected (with or without the echo as the other answer suggests. – Matt B Dec 20 '18 at 21:21
  • @MattB, you're trying to use the <<< operator in a ash-based shell which doesn't support it. In any case, even in zsh or bash which support that operator, that code doesn't make any sense. It redirects the stdin of echo which doesn't read it. It's a wonder how that answer managed to get 10 upvotes. – Stéphane Chazelas May 1 at 22:13
2

This only works if you lose the "echo" on the second line.

content=$(curl -s  -X GET -H "Header:Value" http://127.0.0.1:8200/etc) 
username=$( echo jq -r  '.data.value' <<< "${content}" ) 
echo ${username}
0

You can convert it to a one liner as:

username=$( curl -s  -X GET -H "Header:Value" http://127.0.0.1:8200/etc |  jq -r  '.data.value' ) 
echo ${username}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.