发生这种情况是因为您使用了Runtime.exec(String)
. 切勿使用此功能。这很难预测,只适用于微不足道的情况。始终使用Runtime.exec(String[])
.
由于cd
and&&
不是命令而是 shell 功能,因此您需要手动调用 shell 才能使它们工作:
Runtime.getRuntime().exec(new String[] {
"sh", "-c", "cd /mnt/sdcard/mynote && rm -r aaa"
});
在相关说明中,您永远不应该将未转义的字符串数据传递给 shell。例如,这是错误的:
// Insecure, buggy and wrong!
String target = "aaa";
Runtime.getRuntime().exec(new String[] {
"sh", "-c", "cd /mnt/sdcard/mynote && rm -r " + target
});
正确的方法是将数据作为单独的参数传递给 shell,并从您的命令中引用它们:
// Secure and correct
String target = "aaa";
Runtime.getRuntime().exec(new String[] {
"sh", "-c", "cd /mnt/sdcard/mynote && rm -r \"$1\"", "--", target
});
例如,如果一个文件被命名为*
or My file
,错误的版本将删除一大堆完全不相关的文件。正确的版本没有。