Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Bash Variable to CURL

Tags:

bash

shell

curl

when i give the values like this it works :

curl --silent \ --insecure \ -X POST \ -d '{"Name" : "Vikram"}' \ -H "Content-Type: application/json" \ $restUrl

but when i give it like this :

post="'{\"Name\" : \"Vikram\"}'"    
echo $post   // Prints '{"Name" : "Vikram"}'
echo ${post} // Prints '{"Name" : "Vikram"}'

but the following does not work and throws an 400 error:

curl --silent \ --insecure \ -X POST \ -d ${post} \ -H "Content-Type: application/json" \ $restUrl
like image 618
Vikram Avatar asked Mar 15 '17 15:03

Vikram


People also ask

How do you pass a variable in curl command bash?

Let us say you want to pass shell variable $name in the data option -d of cURL command. There are two ways to do this. First is to put the whole argument in double quotes so that it is expandable but in this case, we need to escape the double quotes by adding backslash before them.

How do you define a variable in curl?

The Curl language naming conventions for variables suggest using lowercase letters and a hyphen to join multiple words (for example, variable-name). is the data type of the variable. Specify any valid data type. type is required if value is not specified.


1 Answers

It seems there are multiple issues.

1) To address the question asked by your title, when you use $post as an argument, the white space in its value causes it to be treated as multiple arguments by Bash. Try putting quotes around it so that it's treated as one argument.

2) I'm guessing you added single quotes to $post, in an attempt to have Bash treat it as a single parameter. Try removing the single quotes.

3) For me at least, all of the backslashes in the curl command were causing it to fail. Maybe you had it split across multiple lines and the copy/paste didn't translate that. I've removed them in my example below.

Putting all together:

post="{\"Name\" : \"Vikram\"}"
curl --silent --insecure -X POST -d "${post}" -H "Content-Type: application/json" $restUrl
like image 76
twm Avatar answered Sep 24 '22 16:09

twm