bash bash脚本中的双感叹号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24980679/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 10:58:14  来源:igfitidea点击:

Double exclamation in bash script

bashunix

提问by Sam

I know when double exclamation is printed, it executes the previous command. But echo !! gives some strange results which I don't understand. For example when typed below command in bash script, it prints echo too as part of the output

我知道当打印双感叹号时,它会执行上一个命令。但是回声!!给出了一些我不明白的奇怪结果。例如,在 bash 脚本中键入以下命令时,它也会将 echo 作为输出的一部分打印出来

echo $$
echo !!
This prints the below output:
echo echo $$
echo 3150
(Why does echo precede every output ?)

回答by Barmar

When you use history substitution, the shell first displays the command that it's about to execute with all the substitutions shown, and then executes it. This is so you can see what the resulting command is, to confirm that it's what you expected.

当您使用历史替换时,shell 首先显示即将执行的命令以及显示的所有替换,然后执行它。这样您就可以看到结果命令是什么,以确认它是您所期望的。

So if you type:

所以如果你输入:

some command
echo !!

the !!is replaced with the contents of the previous command. So it displays and then executes

!!替换为上一个命令的内容。所以它显示然后执行

echo some command

回答by konsolebox

It's caused by history expansion. Quote it instead:

这是历史膨胀造成的。改为引用它:

echo '!!'
echo \!\!

Or disable history expansion:

或者禁用历史扩展:

shopt -u -o histexpand  ## Or
set +H

See History Expansion.

请参阅历史扩展