How to escape the bang (!) character in Linux bash

2020-04-02 03:18发布

问题:

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?

回答1:

Try this:

 echo 'Text text text!'

or

 echo "Text text text"'!'

or

 echo -e "Text text text\x21"


回答2:

Single quote:

echo 'Text Text Text!'

That does it for me.



回答3:

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 hsitory -o histexpand in that script before the echo command did not trigger history expansion issues.



标签: linux bash shell