24

I cannot for the life of me figure out how to escape the ! character in Bash. For example, I want to print this:

Text text text!

I've tried this:

echo "Text text text\!"

but that prints this instead:

Text text text\!

(with an extra backslash).

How can I do this?

ruakh
  • 175,680
  • 26
  • 273
  • 307
Nick
  • 279
  • 1
  • 2
  • 3

3 Answers3

26

Try this:

 echo 'Text text text!'

or

 echo "Text text text"'!'

or

 echo -e "Text text text\x21"
Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • 1
    I'd hesitate to recommend `echo -e` to someone who's mentioned that they have a reason for using double-quotes, since that suggests that they have some sort of variable they're interpolating or whatnot. That could make `echo -e` unsafe. – ruakh Nov 30 '14 at 20:50
9

Single quote:

echo 'Text Text Text!'

That does it for me.

Peregrino69
  • 255
  • 2
  • 11
  • ok thank you, I appreciate that. My goal was to be using double quotes for a couple other reasons, but if I can't figure it out, I will end up using single quotes and making other necessary changes. Thanks! – Nick Nov 30 '14 at 19:29
  • For convenience, [Difference between single and double quotes in Bash](https://stackoverflow.com/questions/6697753/difference-between-single-and-double-quotes-in-bash) – Daniel Chin Dec 17 '22 at 20:27
1

As other answers have indicated the answer to doing this in the general case is to use single quotes (as they do not evaluate history expansion).

As Cyrus's answer indicates you can use double quotes for the main text and single quotes only for the exclamation point if that's what you need. Remember the shell doesn't care how the quoting works out it sees the "words" after the quotes come off.

That all being said in non-interactive contexts history expansion is off by default and so this escaping/etc. is not necessary.

$ cat echo.sh
echo Text Text Text!
$ bash echo.sh
Text Text Text!

In theory you should be able to manually enable history expansion in non-interactive contexts and run into this problem but my quick tests at using set -o history -o histexpand in that script before the echo command did not trigger history expansion issues.

rfay
  • 9,963
  • 1
  • 47
  • 89
Etan Reisner
  • 77,877
  • 8
  • 106
  • 148