Search code examples
bashcurlquotesdouble-quotessingle-quotes

Bash script with a command with lots of single and double quotes


I need to use the curl command:

curl -d '{ "auth_token": "YOUR_AUTH_TOKEN", "text": "Hey, Look what I can do!" }' \http://localhost:3030/widgets/welcome

in a bash script but instead of "Hey, Look what I can do!" after the "YOUR_AUTH_TOKEN"; I need a variable $p .

This is my first time trying a bash script and read the tutorials on quotes and such but I still am not able to make it work.


Solution

  • The easiest thing to do is to read the data from a here document (a type of dynamically created temporary file), rather then trying to quote the entire thing as a string:

    curl -d@- http://localhost:3030/widgets/welcome <<EOF
    { "auth_token": "YOUR_AUTH_TOKEN",
      "text": "$p" }
    EOF
    

    If the argument to -d begins with a @, the remainder of the argument is taken as the name of a file containing the data. A file name of - indicates standard input, and the standard input to curl is supplied by the lines between the EOF tokens.

    The alternative is to double-quote the string and escape all the embedded double quotes. Yuck.

    ... -d "{\"auth_token\": \"YOUR_AUTH_TOKEN\", \"text\": \"$p\"}" ...