[英]Why does this Java code print two arguments?
The below Java code prints two arguments when I pass !clear
as input as shown below. 当我传递!clear
作为输入时,下面的Java代码打印两个参数,如下所示。
class Test{
public static void main(final String... arguments){
for(String argument : arguments){
System.out.println(argument);
}
}
}
Output: 输出:
$ java Test !clear
java Test clear
clear
UPDATE UPDATE
Using any linux command in place of clear
produces the same result. 使用任何linux命令代替clear
产生相同的结果。
$ java Test !pwd
java Test pwd
pwd
$ java Test !ls
java Test ls
ls
I am aware that this has got something to do with history expansion in bash and I can escape the ! 我知道这与bash中的历史扩展有关,我可以逃脱! character to solve this issue. 解决这个问题的角色。
However, I am curious to know the exact reason why this code prints the above two lines as output. 但是,我很想知道此代码将上述两行打印为输出的确切原因。 Could somebody please explain? 有人可以解释一下吗?
You are working within a Unix/Linux shell, probably bash
. 您正在Unix / Linux shell中工作,可能是bash
。 The !
的!
character is a special character in the Unix shell, and thus your command is considered a history expansion. character是Unix shell中的特殊字符,因此您的命令被视为历史扩展。
In history expansion, the usual thing that happens is that the shell shows you what the command expands to. 在历史扩展中,通常发生的事情是shell会向您显示命令扩展到的内容。 The expansion of !clear
will simply be clear
provided that you had the command clear
in your history , and the expanded command will therefore be java Test clear
. 的扩张!clear
将简单地clear
规定,您必须在命令clear
在你的历史 ,因此扩展命令将java Test clear
。 The shell then runs the command. 然后shell 运行命令。 Java runs and only sees one argument - clear
, and that's what it prints. Java运行并且只看到一个参数 - clear
,这就是它打印的内容。
If instead, you run 相反,如果你运行
java Test '!clear'
(With the single quotes!) (用单引号!)
Java will get the argument !clear
as is, without history expansion. Java将获得参数!clear
,没有历史扩展。
If you use a word that is not in the shell's history of commands, you'll get an "event not found error". 如果您使用的单词不在shell的命令历史记录中,您将收到“未找到事件错误”。 If you use a word that, in your shell history, started a command with arguments, the entire command with all its arguments will be substituted. 如果你使用一个单词,在你的shell历史中,用一个参数启动一个命令,整个命令及其所有参数都将被替换。 This is all part of bash
and not Java. 这是bash
一部分,而不是Java。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.