如何在 Linux bash shell 中转义 bang (!) 字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27216951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to escape the bang (!) character in Linux bash shell?
提问by Nick
I cannot for the life of me figure out how to escape the !
character in Bash. For example, I want to print this:
我一生都无法弄清楚如何!
在 Bash 中逃避角色。例如,我想打印这个:
Text text text!
Text text text!
I've tried this:
我试过这个:
echo "Text text text\!"
but that prints this instead:
但这会打印出来:
Text text text\!
Text text text\!
(with an extra backslash).
(带有额外的反斜杠)。
How can I do this?
我怎样才能做到这一点?
回答by Cyrus
Try this:
尝试这个:
echo 'Text text text!'
or
或者
echo "Text text text"'!'
or
或者
echo -e "Text text text\x21"
回答by Peregrino69
Single quote:
单引号:
echo 'Text Text Text!'
That does it for me.
这对我有用。
回答by Etan Reisner
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 answerindicates 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.
正如赛勒斯的回答所指出的,如果您需要,您可以对正文使用双引号,仅对感叹号使用单引号。请记住,shell 并不关心引用是如何工作的,它会在引号脱落后看到“单词”。
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.
从理论上讲,您应该能够在非交互式上下文中手动启用历史扩展并遇到这个问题,但我set -o hsitory -o histexpand
在该脚本中使用的快速测试在echo 命令没有触发历史扩展问题之前。