Dervin Thunk Dervin Thunk - 5 months ago 23
Bash Question

How do I expand a variable inside single quotes?

I want to run this simple bash script:

curl https://www.googleapis.com/urlshortener/v1/url?key=MyKey -H \\
'Content-Type: application/json' -d '{"longUrl": "$1"}'


but bash does not expand the
$1
because of the single quotes after
-d
. Google returns, expectedly, and error:

{
"error": {
"errors": [
{
"domain": "global",
"reason": "invalid",
"message": "Invalid Value",
"locationType": "parameter",
"location": "resource.longUrl"
}
],
"code": 400,
"message": "Invalid Value"
}
}


How do I expand the
$1
inside the single quotes of the json object sent by
-d
in
curl
?

This question does seem to be a duplicate, but I cannot figure out the answer from the other ones. I'm providing the script in the hopes it will be useful for someone else as a contribution.

Answer

You could just use double quotes, escaping the ones inside the JSON string:

curl https://www.googleapis.com/urlshortener/v1/url?key=MyKey -H \\
  'Content-Type: application/json' -d "{\"longUrl\": \"$1\"}"
Comments