转载:https://blog.youkuaiyun.com/arthur503/article/details/37592571
linux命令行中,双引号中的感叹号将被解释为历史命令。
命令:
test -e ttt/ && echo "file exist!" || echo "file Not exist!"
输出:
bash: !": event not found
命令:
test -e ttt/ && echo "file exist" || echo "file Not exist"
输出:
file exist
实验如下:
-
arthur@E430 ~/workspace/test]$ls
-
bin HelloWorld.class HelloWorld.java re t2.sh t.sh
-
d HelloWorld.jar HelloWorld.java~ t1.sh t.py
-
[arthur@E430 ~/workspace/test]$echo "!!"
-
echo "ls "
-
ls
-
[arthur@E430 ~/workspace/test]$pwd
-
/home/arthur/workspace/test
-
[arthur@E430 ~/workspace/test]$echo "!l"
-
echo "ls "
-
ls
-
[arthur@E430 ~/workspace/test]$echo "!!"
-
echo "echo "ls ""
-
echo ls
-
[arthur@E430 ~/workspace/test]$echo "!!"
-
echo "echo "echo "ls """
-
echo echo ls
[arthur@E430 ~/workspace/test]$
如果是想要输出感叹号,可以:
1. 使用单引号。
一般要输出特殊符号,可以用单引号'引文',或者\。 这时候最好用单引号,如: echo 'Hello World !' 比如要输出That's good.就用 echo "That's good."
2.
\! 表示感叹号 比如echo Hello\ World\ \!, linux很多符号都是用转义符"\"来表示的,尽量不要用双引号“”。 原因你自己 echo "Hello World !",就会发现输出错误的, 而 echo "Hello World \!",又发现连“\”也一起输出了
查资料如下:
在双引号中,感叹号(!)的含义根据使用的场合有所不同,在命令行环境,它将被解释为一个历史命令,而在脚本中,则不会有特殊含义。
Advanced Bash-Scripting Guide: 5.1. Quoting Variables 写道
Encapsulating "!" within double quotes gives an error when used from the command line. This is interpreted as a history command. Within a script, though, this problem does not occur, since the Bash history mechanism is disabled then.
在命令行环境,感叹号(!)称之为“历史扩展字符(the history expansion character)”。
[root@jfht ~]# pwd
/root
[root@jfht ~]# echo "!"
-bash: !: event not found
[root@jfht ~]# echo "!pwd"
echo "pwd"
pwd
[root@jfht ~]#
在脚本中使用感叹号,将不会进行历史扩展。
参考资料:
http://codingstandards.iteye.com/blog/1166282
在双引号中,感叹号(!)的含义根据使用的场合有所不同,在命令行环境,它将被解释为一个历史命令,而在脚本中,则不会有特殊含义。
Advanced Bash-Scripting Guide: 5.1. Quoting Variables 写道
Encapsulating "!" within double quotes gives an error when used from the command line. This is interpreted as a history command. Within a script, though, this problem does not occur, since the Bash history mechanism is disabled then.
在命令行环境,感叹号(!)称之为“历史扩展字符(the history expansion character)”。
[root@jfht ~]# pwd
/root
[root@jfht ~]# echo "!"
-bash: !: event not found
[root@jfht ~]# echo "!pwd"
echo "pwd"
pwd
[root@jfht ~]#
在脚本中使用感叹号,将不会进行历史扩展。