Home > Software engineering >  Feed an array with spaces to curl
Feed an array with spaces to curl

Time:07-19

Why curl invoked with

curl_options=("--verbose" "--user-agent 'Mozilla compatible'"); \
curl $(echo "${curl_options[@]}") icanhazip.com

returns an error: "curl: (6) Could not resolve host: compatible", that is, it does not understand the quoted string 'Mozilla compatible' as a two-word whole?

The very same command curl_options=("--verbose" "--user-agent 'Mozilla compatible'"); echo "${curl_options[@]}" shows that the string is quoted properly: --verbose --user-agent 'Mozilla compatible'

CodePudding user response:

When you run

mozilla --verbose --user-agent 'Mozilla compatible'

mozilla sees three arguments:

  1. --verbose
  2. --user-agent
  3. Mozilla compatible

The array should contain the same three words.

curl_options=(
   --verbose
   --user-agent
   'Mozilla compatible'
)

Then

curl "${curl_options[@]}" icanhazip.com  # no echo or command substitution

The quotes around Mozilla compatible are not part of the argument; they are used by the shell to prevent Mozilla and compatible from being treated as two separate arguments.

You could write

curl_options=(
    --verbose
    --user-agent='Mozilla compatible'
)

This defines two different arguments, but curl itself will treat the single argument --user-agent=Mozilla compatible the same way it treats the adjacent pair of arguments --user-agent and Mozilla compatible.

  • Related