问题
I'm building a shell script (trying to be POSIX compliant) and I'm stuck in an issue. The script is supposed to receive an URL and do some things with it's content.
myscript www.pudim.com.br/?&args=ok
The thing is, the ampersand symbol is interpreted as a command additive, and giving to my script only the www.pudim.com.br/?
part as an argument.
I know that the right workaround would be to surround the URL with quotes but, because I need to use this script several times in a row, I wanted to paste the URL's without having to embrace it with quotes every time.
Is there some way to get the full URL argument, somehow bypassing the ampersand?
回答1:
Quotes for full URL
Wrapping the URL in quotes will be your only chance. See popular shell utility curl, as it states for its core argument URL:
When using [] or {} sequences when invoked from a command line prompt, you probably have to put the full URL within double quotes to avoid the shell from interfering with it. This also goes for other characters treated special, like for example '&', '?' and '*'.
See also this question and that.
Extra argument(s) for specifying query parameters
You can also pass query parameter (key-value pair) as separate argument. So you can bypass &
as separator. See curl's -F
option:
-F, --form <name=content>
Read URL from STDIN
If your script allows user interaction you could read
the unescaped URL (including metachars as &
) from an uninterpreted input-source. See this tutorial.
回答2:
You can escape just the ampersand; quotes effectively escape every character between them.
myscript www.pudim.com.br/\?\&args=ok # The ? should be escaped as well
There is no solution that lets you avoid all quoting, as &
is a shell metacharacter whose unquoted meaning cannot be disabled. The &
terminates the preceding command, causing it to be run in a background process; adding some redundant whitespace, you attempt is the same as
myscript www.pudim.com.br/? &
args=ok
Unescaped, the ?
will cause the URL to be treated as a pattern to expand. However, it's unlikely the pattern will match any existing file, and bash
's default behavior is to treat an unmatched pattern literally. (The failglob
option will treat it as an error, and the nullglob
option will make the URL disappear completely from the command line, but neither option is enabled by default.)
来源:https://stackoverflow.com/questions/59445529/how-to-bypass-an-ampersand-without-using-quotes-when-receiving-an-url-as-an