简体   繁体   中英

How to echo variable inside single quotes using Bash?

users.I want to run a curl command with a bash script. (below command works perfectly in terminal)

curl -i -H "Content-Type: application/json" -X POST -d '{"mountpoint":"/gua-la-autentica-1426251559"}' http://127.0.0.1:5000/connect

But unable to run this command in bash. When mountpoint value is given in a variable($final).

final="/gua-la-autentica-1426251559"
curl -i -H "Content-Type: application/json" -X POST -d '{"mountpoint":'$final'}' http://127.0.0.1:5000/connect

Could someone please help me, how to echo variable inside single quotes?

JSON string values should be quoted and so should parameter expansions. You can achieve this by using double quotes around the entire JSON string and escaping the inner double quotes, like this:

curl -i -H "Content-Type: application/json" -X POST -d "{\"mountpoint\":\"$final\"}" http://127.0.0.1:5000/connect

As mentioned in the comments, a more robust approach would be to use a tool such as jq to generate the JSON:

json=$(jq -n --arg final "$final" '{ mountpoint: $final }')
curl -i -H "Content-Type: application/json" -X POST -d "$json" http://127.0.0.1:5000/connect

I'd probably do it with a printf format. It makes it easier to see formatting errors, and gives you better control over your output:

final="/gua-la-autentica-1426251559"

fmt='{"mountpoint":"%s"}'

curl -i -H "Content-Type: application/json" -X POST \
  -d "$(printf "$fmt" "$final")" \
  http://127.0.0.1:5000/connect

I don't know where you're getting $final in your actual use case, but you might also want to consider checking it for content that would break your JSON. For example:

Portable version:

if expr "$final" : '[A-Za-z0-9./]*$'; then
  curl ...
else
  echo "ERROR"
fi

Bash-only version (perhaps better performance but less portable):

if [[ "$final" ]~ ^[A-Za-z0-9./]*$ ]]; then
  curl ...
...

Checking your input is important if there's even the remote possibility that your $final variable will be something other than what you're expecting. You don't have valid JSON anymore if it somehow includes a double quote.

Salt to taste.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM