How to echo variable inside single quotes using Bash?

后端 未结 2 1916
无人共我
无人共我 2021-01-21 21:58

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 \'{\"         


        
相关标签:
2条回答
  • 2021-01-21 22:35

    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
    
    0 讨论(0)
  • 2021-01-21 22:35

    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.

    0 讨论(0)
提交回复
热议问题