简体   繁体   English

如何在bash中的双引号之间写入“!”符号?

[英]How to write “!” symbol between double quotes in bash?

I can't figure out how to write ! 我不知道该怎么写! symbol in bash scripts when putting it in double quotes strings. bash脚本中的符号放在双引号字符串中时。

For example: 例如:

var="hello! my name is $name! bye!"

Something crazy happens: 疯狂的事情发生了:

Boda-Cydo-Sith-Computer:~$ age=20
Boda-Cydo-Sith-Computer:~$ name='boda'
Boda-Cydo-Sith-Computer:~$ var="hello! my name is $name! bye!"

When I press enter at last command the command repeats itself (types itself) without the last ! 当我在最后一个命令上按Enter键时,该命令会重复自身(键入自身)而没有最后一个! :

Boda-Cydo-Sith-Computer:~$ var="hello! my name is $name! bye"

If I press enter again 如果我再次按Enter

Boda-Cydo-Sith-Computer:~$ var="hello! my name is $name bye"

If i press enter again it disappears nothing gets output 如果我再次按回车键,它消失了,没有任何输出

Boda-Cydo-Sith-Computer:~$ 

If I try this: 如果我尝试这样做:

Boda-Cydo-Sith-Computer:~$ echo "hello\! my name is $name\! bye\!"

Then it outputs: hello\\! my name is boda\\! bye\\! 然后输出: hello\\! my name is boda\\! bye\\! hello\\! my name is boda\\! bye\\!

If i use single quotes then my name doesn't get expanded: 如果我使用单引号,则我的名字不会扩展:

Boda-Cydo-Sith-Computer:~$ echo 'hello! my name is $name! bye!'

Outputs are: hello! my name is $name! bye! 输出为: hello! my name is $name! bye! hello! my name is $name! bye!

I have it working this way: 我有这样工作:

Boda-Cydo-Sith-Computer:~$ echo "hello"'!'" my name is $name"'!'" bye"'!'

But it's one big mess with " and ' impossible to understand/edit/maintain/update. 但这与"'是一团糟,无法理解/编辑/维护/更新。

Can anyone help? 有人可以帮忙吗?

If history expansion is enabled (which it usually is, unless you specifically disabled it), ! 如果启用了历史记录扩展(通常会启用,除非您特别禁用它) ! followed by something that is not whitespace will attempt to find the last command in history that began with the string that follows it. 后跟非空格的内容将尝试查找历史记录中的最后一条命令,该命令以其后的字符串开头。

Thus the only problematic occurrence of ! 因此,唯一有问题的发生! in your code is in bye! 在您的代码中bye! . You can either add a trailing whitespace (which certainly feels hacky, to say the least), or you can put it in single quotes like you did, but there's no need to do this with the other ! 您可以添加尾随空格(至少可以说确实令人讨厌),也可以像以前一样将其放在单引号中,但不需要与其他空格一起使用! (because they are followed by a whitespace), so the command is not really that hard to read / edit: (因为它们后面是空格),因此该命令并不是很难阅读/编辑的地方:

var="hello! my name is $name! bye"'!'

That's all you need. 这就是您所需要的。 Or, of course, if you do not intend to use the shell's history expansion capabilities, you can always disable it with set +o histexpand and then this won't be a problem. 或者,当然,如果您不打算使用Shell的历史记录扩展功能,则可以始终使用set +o histexpand禁用它,这样就不会有问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM