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

3
  • 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. Commented Jan 5, 2021 at 18:38
  • email="[email protected]" ; echo $(printf '{"email":"%s"}' $email) Commented Jan 5, 2021 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='[email protected]'; echo $(printf '{"email": "%s"}' $email)); and that's ignoring what happens if you have a value that could be parsed as a glob expression... Commented Jan 5, 2021 at 18:47

1 Answer 1

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":[email protected],"password":"validPassword"}

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
This wouldn't be the first time someone didn't debug sufficiently to tell the actual problem.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.