I have a posix sh script that runs another command. The second command can have zero, one or multiple options passed. These options are passed as an env var, e.g. $OPTIONS. However, some of the options can have spaces in them.
E.g. If my executed command is curl, then my option is CURL_OPTIONS.
#!/bin/sh
# do some processing
curl $CURL_OPTIONS https://some.example.com
As long as none of the CURL_OPTIONS contains whitespace, I am fine, e.g.
CURL_OPTIONS="--user me:pass --user-agent foo"
However, if the options contain space, the sh expands it out and treats each like its own var:
CURL_OPTIONS="--header 'Authorization: token abcdefg'"
I can run curl --header 'Authorization: token abcdefg' https://some.url.com, since the sh will interpret the single quotes ' and pass Authorization: token abcdefg as a single parameter to curl, and all is fine.
However, because I am working with a var, the sh expands it out upon seeing $CURL_OPTIONS and does not interpret the single-quoted Authorization: token abcdefg as a single parameter. The result of the above is:
curl: (6) Could not resolve host: token
curl: (6) Could not resolve host: abcdefg'
(Note that it even treats the single quote as part of abcdefg'.)
Yes, I have seen this question and its answers , none of which seems to work in this case.
UPDATE:
Oh, now this is interesting https://stackoverflow.com/a/31485948/736714
Why didn't I think of xargs?
Actually, this works.
CURL_OPTIONS=(--header "Authorization: token abcdefg")
curl "${CURL_OPTIONS[@]}" www.example.com
How to pass quoted arguments from variable to bash script
UPDATE: I'm guessing this next snippet should be POSIX-compliant (it's a bit of an escape-hell, though)
CURL_OPTIONS="--header \\\"Authorization:\ token\ abcdefg\\\""
eval set -- $CURL_OPTIONS
curl "$@" www.example.com
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With