If you are writing a bash script to call a curl command and you want to pass variable values to it, read this…

CodingImage
If you are writing a bash script to call a curl command and you want to pass variable values to it, you may find a hard time determining how to go about it. I did!! I consulting with lots of pages, and nothing seemed to tell me what I want.

Here’s what I eventually did.

Take this example. I am using curl to call the sendgrid API, as you can see below. (I don’t have all the variables, but they were all strings like THESUBJECT and THECONTENT.).

The trick is in the use of single and double quotes. For the variables, they are in double quotes. But notice the use of single and double quotes in the curl command:


TOYOU="noone@gmail.com"
THESUBJECT="once again!"
THECONTENT="Looks good!"
curl --request POST --url https://api.sendgrid.com/v3/mail/send \
--header 'Authorization: Bearer '$AUTH_TOKEN \
-H 'Content-Type: application/json' \
--data '{"personalizations": [{"to": [{"email": '\"$TOYOU\"'}]}],"from": {"email": '\"$FROMME\"'}, "subject": '\""$THESUBJECT"\"', "content": [{"type": "text/plain", "value": '\""$THECONTENT"\"' }]}'

Let’s look at the variables in that curl command.

$AUTH_TOKEN has no quotes around it. In fact, it is up against a single quote on its left. That single quote ends the string Authorization: Bearer and let’s the script fill in the value of $AUTH_TOKEN.

Now look at $TOYOU AND $FROMME. Both of those variables have no blanks in them. So there is a single quote-slash-double quote on the left and a slash-double quote-single quote to the right.

that is different than $THESUBJECT and $THECONTENT. Those strings have blanks in them. For them, there is a single quote-slash-double quote-double quote to the left of them and a double quote-slash-double quote-single quote to the right.

It’s crazy but true. Good luck with it!

(Photo by Shahadat Rahman on Unsplash )

Comments are closed.