为什么有些命令失败?
发生这种情况是因为传递给命令的命令Runtime.exec(String)不在外壳中执行。Shell为程序提供了许多常见的支持服务,并且当Shell不在附近时,该命令将失败。
When do commands fail?
只要命令依赖于Shell功能,它就会失败。壳做了很多我们通常不会想到的常见,有用的事情:
- The shell splits correctly on quotes and spaces
这样可以确保文件名”My File.txt”仍为单个参数。
Runtime.exec(String)天真地在空格上分割,并将其作为两个单独的文件名传递。这显然失败了。
- The shell expands globs/wildcards
运行时
ls *.doc,shell将其重写为
ls letter.doc notes.doc。
Runtime.exec(String)不会,它只是将它们作为参数传递。
ls不知道是什么
*,所以命令失败。
- The shell manages pipes and redirections.
运行时
ls mydir > output.txt,外壳程序打开
“ output.txt”以显示命令输出,并将其从命令行中删除,给出
ls mydir。
Runtime.exec(String)没有。它只是将它们作为参数传递。
ls不知道什么>意思,所以命令失败。
- The shell expands variables and commands
当你运行
ls "$HOME"或时
ls "$(pwd)",shell将其重写为
ls /home/myuser。
Runtime.exec(String)不会,它只是将它们作为参数传递。
ls不知道什么
$意思,所以命令失败。
What can you do instead?
有两种方法可以执行任意复杂的命令:
简单而草率:委托给一个shell。
你可以只使用
Runtime.exec(
String[])(注意array参数)并将命令直接传递到可以完成所有繁重任务的shell:
// Simple, sloppy fix. May have security and robustness implicationsString myFile = "some filename.txt";String myCommand = "cp -R '" + myFile + "' $HOME 2> errorlog";Runtime.getRuntime().exec(new String[] { "bash", "-c", myCommand });安全可靠:承担外壳的责任。
这不是可以机械地应用的修复程序,而是需要了解Unix执行模型,shell的功能以及如何执行相同的操作。但是,通过将外壳从图片中取出,可以获得可靠,安全和可靠的解决方案。这由来促进ProcessBuilder。
前面示例中要求某人处理1.引号,2。变量和3.重定向的命令可以写为:
String myFile = "some filename.txt";ProcessBuilder builder = new ProcessBuilder( "cp", "-R", myFile, // We handle word splitting System.getenv("HOME")); // We handle variablesbuilder.redirectError( // We set up redirections ProcessBuilder.Redirect.to(new File("errorlog")));builder.start();


