3

I am working on simple curl POST script and I have problem with string interpolation of a variable that is initialized with data from a script. Let me describe it:

#!/bin/bash

EMAIL=$(source ./random_email_generator.sh) #this generates some random string 
echo "$EMAIL" #here email is printed well
curl --insecure --header "Content-Type: application/json" \
  --request POST \
  --data '{"email":'"$EMAIL"',"password":"validPassword"}' \ #problem lies here because email is always empty string 
 http:/ticketing.dev/api/users/signup 

To sum up, there is a lot of quotes and double quotes here and it is abit mixed up, how can I resolve value of EMAIL in place of json body?

Thanks in advance

Mateusz Gebroski
  • 1,274
  • 3
  • 26
  • 57
  • Could you run this with `bash -x yourscript` and [edit] the question to include the output? Your code isn't exactly following best practices -- a sufficiently surprising email address could generate invalid JSON -- but it should _work_, even so. – Charles Duffy Jan 05 '21 at 18:38
  • `email="foo@mar.com" ; echo $(printf '{"email":"%s"}' $email)` – Abelisto Jan 05 '21 at 18:44
  • @Abelisto, ...well, that's got its own problems, owing mostly to lack of quotes. See what happens if you have a character from `IFS` present in your email address (f/e: `IFS=.; email='foo@bar.com'; echo $(printf '{"email": "%s"}' $email)`); and that's ignoring what happens if you have a value that could be parsed as a glob expression... – Charles Duffy Jan 05 '21 at 18:47

1 Answers1

4

The variable is being interpolated properly. The problem is that you're not wrapping it in double quotes, so you're creating invalid JSON.

curl --insecure --header "Content-Type: application/json" \
  --request POST \
  --data '{"email":"'"$EMAIL"'","password":"validPassword"}' \
  http:/ticketing.dev/api/users/signup 

When you want to see what the command actually looks like, put echo before curl or run the script with bash -x. You would have seen

--data {"email":foo@bar.com,"password":"validPassword"}

It would be better if you used the jq tool to manipulate JSON in bash scripts.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Heh, quite right -- I missed the lack of literal double quotes. Still, the email address _is_ there in the body, just not substituted in in a way that makes it valid JSON; so the OP's claim that there's an empty string in its place is confusing to me. – Charles Duffy Jan 05 '21 at 18:39
  • This wouldn't be the first time someone didn't debug sufficiently to tell the actual problem. – Barmar Jan 05 '21 at 18:41