Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

bash

jq

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.

like image 905
dotHello Avatar asked Sep 13 '25 00:09

dotHello


2 Answers

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

oguz ismail


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

like image 38
Mayank Madhav Avatar answered Sep 14 '25 14:09

Mayank Madhav