0

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:~$ 
karthik nair
  • 233
  • 3
  • 12

1 Answers1

1

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.

karthik nair
  • 233
  • 3
  • 12
  • @terdon and @karthik 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
  • @StéphaneChazelas it was someone else who edited and made the answer look like that. I did rollback. check now – karthik nair Jul 30 '22 at 14:32
  • 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
  • 1
    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
  • Both works here. why cant we use 'newer' versions of bash? – karthik nair Jul 30 '22 at 14:46
  • Oh wow, sorry @StéphaneChazelas and Karthik, I had misread the question as being about 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
  • @terdon Thanks. Much appreciated – karthik nair Jul 31 '22 at 09:55