dotHello
dotHello

Reputation: 51

Passing variables (containing spaces) to curl --data field

Arguments containing spaces will not properly pass to the curl command. Quotes are not passed correctly in the --data field.

If I just echo the variable 'curlData' that I use in the curl command I get everything as it should be; ex :

$echo $curlData
'{"name":"jason","description","service"}'

I don't understand why curl dont expend this 'curlData' variable as expected:

curl --data '{"name":"jason","description","service"}'

Here's a sample of my code:

read -p "Name : " repoName
read -p "Description []: " repoDescription

curlData="'"{'"'name'"':'"'$repoName'"','"'descripton'"':'"'$repoDescription'"'}"'"

curl --data $curlData $apiURL 

And the error:

curl: (3) [globbing] unmatched close brace/bracket in column 26

Thank your for your help, I feel i'm in Quote-ception right now.

Upvotes: 3

Views: 3673

Answers (3)

Mayank Madhav
Mayank Madhav

Reputation: 499

I had similar issue, which was very difficult to even understand. I used the below construct in a number of curl commands present in my shell script. It always worked like a charm. Until one fine day I had to pass a variable which was string containing spaces (eg. modelName="Abc def").

  curl -X 'PUT' \
  'http://localhost:43124/api/v1/devices/'$Id'' \
  -H 'accept:*/*' \
  -H 'Authorization:Bearer '$token'' \
  -H 'Content-Type:application/json' \
  -d '{
  "modelName":"'$modelName'",
  "serialNumber":"'$childSN'"
}'

Worked for me after the below change

 curl -X 'PUT' \
  'http://localhost:43124/api/v1/devices/'$Id'' \
  -H 'accept:*/*' \
  -H 'Authorization:Bearer '$token'' \
  -H 'Content-Type:application/json' \
  -d '{
  "modelName":'\""$modelName"\"',
  "serialNumber":"'$childSN'"
}'

I took help from the accepted answer by @oguz. Pasting this response , just in case anyone is in similar situation

Upvotes: 1

oguz ismail
oguz ismail

Reputation: 50750

  1. Quote all variable expansions,
  2. To make sure that curlData is a valid JSON value with properly escaped special-characters etc., use for producing it.
curlData="$(jq --arg name "$repoName" --arg desc "$repoDescription" -nc '{name:$name,description:$desc}')"
curl --data "$curlData" "$apiURL"

Upvotes: 4

vintnes
vintnes

Reputation: 2030

If you have access to any form of package management, I highly recommend jo.

curlData=$(jo name="$repoName" description="$repoDescription")
curl -d "$curlData" "$apiURL"

Upvotes: 0

Related Questions