3

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?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
deitch
  • 14,019
  • 14
  • 68
  • 96
  • using `eval` is an option? https://serverfault.com/a/875449/94862 – nbari Jul 21 '18 at 20:07
  • Possible duplicate of [Bash: Reading quoted/escaped arguments correctly from a string](https://stackoverflow.com/questions/26067249/bash-reading-quoted-escaped-arguments-correctly-from-a-string) – John Kugelman Jul 21 '18 at 20:18
  • Yeah, I found the `xargs` recommendation afterwards, but decided to leave it up. – deitch Jul 22 '18 at 06:42

1 Answers1

3

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
neeohw
  • 555
  • 4
  • 12
  • 3
    Arrays aren't available in POSIX sh. – John Kugelman Jul 21 '18 at 20:17
  • Yeah, that is escape hell, and @JohnKugelman is right that I need POSIX, not `bash`. The problem with this answer is that it requires, as you said, "escape-hell", which I cannot impose on the users of the command. – deitch Jul 22 '18 at 06:43