How to echo variable inside single quotes using Bash?

后端 未结 2 1940
无人共我
无人共我 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

    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.

提交回复
热议问题