More broadly, how to echo ! in bash without space in between
karthik@cosmic:~$ echo "Hello!World"
bash: !World: event not found
karthik@cosmic:~$ echo "Hello\!World"
Hello\!World
karthik@cosmic:~$
More broadly, how to echo ! in bash without space in between
karthik@cosmic:~$ echo "Hello!World"
bash: !World: event not found
karthik@cosmic:~$ echo "Hello\!World"
Hello\!World
karthik@cosmic:~$
Thanks to someone, the solution is simple.
Remove those double quotes and escape the !
:
echo Hello\!World
or with bash 4.3 or newer, use double quotes but make sure the !
is immediately followed by the closing quote:
echo "Hello!""World"
From the release notes in bash 4.3:
l. The history expansion character (!) does not cause history expansion when followed by the closing quote in a double-quoted string.
Best is to use single quotes inside which all characters lose their special meaning¹.
echo 'Hello!World'
Or disable csh-style history expansion altogether with:
histchars=
Or:
set +o histexpand
Or:
set +H
Note that history expansion is only enabled by default when bash is interactive, not in scripts.
As long as the deprecated `...`
form of command substitution is not also used, as inside it, \
retains a special meaning even inside single quotes.
Hello World!
is not the same as Hello!World
when it comes to csh-style history expansion interference.
– Stéphane Chazelas
Jul 30 '22 at 14:29
echo Hello!World
doesn't work. !
is even more a problem outside of "..."
than inside though outside, you can escape it with backslash.
– Stéphane Chazelas
Jul 30 '22 at 14:34
echo "Hello""!""World"
doesn't work either in older versions of bash
. See the linked duplicate for details.
– Stéphane Chazelas
Jul 30 '22 at 14:36
Hello World!
and not Hello!World
which is indeed a different issue. Karthik, I escaped the !
in your unquoted example since that won't work otherwise. And there is no reason we can't use newer versions, it's just that not everyone has newer versions so we like to point out limitations of our answers.
– terdon
Jul 30 '22 at 15:17