The bash manual entry for double quotes (https://www.gnu.org/software/bash/manual/html_node/Double-Quotes.html) states:
If enabled, history expansion will be performed unless an ‘!’ appearing in double quotes is escaped using a backslash. The backslash preceding the ‘!’ is not removed.
Why is there a special case made for !
? If I escape a $
(for example) the backslash doesn't appear in the output (e.g. compare echo "\$"
-> $
and echo "\!"
-> \!
).
What do if I just want a literal !
inside double quotes?
A limitation I have for this problem is that I'm unable to easily manipulate the form of the bash invocation. By this I mean I'm stuck executing the command using a single double-quoted string, i.e.
my-command "a string I generate in an external program that may contain !"
I can control how the string is generated, but I can't split it up on the command line (e.g. something like "part1"\!"part2"
wouldn't work for me.)
echo -e "\x22\x21\x22"
– George Vasiliou Jan 31 '20 at 01:15cmd "$var"
orcmd "$(othercmd)"
), then there's no problem at all. If you're constructing a command line to be passed to bash for execution, just replace each exclamation mark with"'!'"
(that is, a double-quote, a single-quote, and exclamation mark, another single-quote, and finally a double-quote). – Gordon Davisson Jan 31 '20 at 09:32