bashshell

How to build a dynamic CURL and attribute result to a variable?


I have to execute a CURL command in which the URL is dynamic, in other words comming from a variable or parameter and I need to attribute the response of the CURL command to a variable.

This is how I am trying to do it:

#!/bin/bash
googleUrl="https://google.com";
googleResponse="$(curl --insecure --location \"$googleUrl\")";
echo $googleResponse;

Getting the error: curl: (3) URL rejected: Port number was not a decimal number between 0 and 65535.

But if I replace the googleUrl variable by the actual url in the curl command I get the html response as expected.


Solution

  • You have a quote issue, you need:

    #!/bin/bash
    googleUrl="https://google.com";
    googleResponse="$(curl --insecure --location "$googleUrl")";
    echo "$googleResponse"
    

    Learn how to quote properly in shell, it's very important :

    "Double quote" every literal that contains spaces/metacharacters and every expansion: "$var", "$(command "$var")", "${array[@]}", "a & b". Use 'single quotes' for code or literal $'s: 'Costs $5 US', ssh host 'echo "$HOSTNAME"'. See
    http://mywiki.wooledge.org/Quotes
    http://mywiki.wooledge.org/Arguments
    wiki.bash-hackers.org/syntax/words
    unix.stackexchange.com/when-is-double-quoting-necessary