0

I am learning to work with Bash and APIs, and am currently stuck on a problem related to nested variables.

The basic action I wish to do looks like this:

name="peter"; country="uk";    
gender=$(http -b GET "https://api.genderize.io/?$name=peter&country_id=$uk" | jq -e '.gender');
echo $gender

output is

"male"

The complete action I want to take looks like this:

while read name <&3 && read country <&4

    do gender=$(http -b GET "https://api.genderize.io/?name=$name&country_id=$country" | jq -e '.gender')

    echo "$name : $gender" >> namesorted.txt 

    sleep 0.1 

done 3<namelist.txt 4<countrylist.txt

but the output is null, which means that the request wasn't sent correctly:

Peter : null
Edouard : null
Henri : null
Anabelle : null
Nonso : null
Tom : null

What's wrong with my code? And is there a way for me to see the query sent by the code for debugging purposes?

edit: it ended up being a formatting mistake, as pointed out in the comments. Thanks!

maqueiouseur
  • 89
  • 1
  • 7
  • `echo "$name : $gender" >> namesorted.txt` BTW (single parameter to echoing) Also you do not need semicolon at each line in bash script. Line breaks is enough. Not sure does it helps but fix those errors first. – Abelisto Mar 22 '18 at 00:50
  • 2
    You have single-quotes around the URL, and variables don't get expanded in single-quotes. Use double-quotes instead. See ["Difference between single and double quotes in Bash"](https://stackoverflow.com/questions/6697753/difference-between-single-and-double-quotes-in-bash) and ["When to wrap quotes around a shell variable?"](https://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-shell-variable). – Gordon Davisson Mar 22 '18 at 00:53
  • Abelisto thanks for the the echo writing best practice, I didn't notice it because the output was as I expected it to be. For the semicolon, it was just a convnient way for me to be able to quickly make a one line query out of the code to test it in my shell. I corrected it. @GordonDavisson thanks that ended up being the problem. As you can see in my basic example I did use the correct double quotes, as I know that they allow variable expansion; but then I got confused in the full script with the single quote around the jq argument... – maqueiouseur Mar 22 '18 at 02:28

1 Answers1

0

As pointed in the comments, it ended up being a formatting mistake:

the use of double quotes in the initial script is correct, because it allows variables to be exanded:

gender=$(http -b GET "https://api.genderize.io/?$name=peter&country_id=$uk" | jq -e '.gender')  

But in my full script I got mixed up with the single quotes, which kept the variables from being expanded. I fixed it in the original question, and the code works.

Thanks to @Gordon Davidsson for identifying the issue.

maqueiouseur
  • 89
  • 1
  • 7