如何从 Java 代码运行 Unix shell 脚本?

如何从 Java 代码运行 Unix shell 脚本?

问题描述:

从 Java 运行 Unix 命令非常简单.

It is quite simple to run a Unix command from Java.

Runtime.getRuntime().exec(myCommand);

但是可以从 Java 代码运行 Unix shell 脚本吗?如果是,从 Java 代码中运行 shell 脚本是否是一个好习惯?

But is it possible to run a Unix shell script from Java code? If yes, would it be a good practice to run a shell script from within Java code?

你真的应该看看 流程构建器.它真的是为这种事情而构建的.

You should really look at Process Builder. It is really built for this kind of thing.

ProcessBuilder pb = new ProcessBuilder("myshellScript.sh", "myArg1", "myArg2");
 Map<String, String> env = pb.environment();
 env.put("VAR1", "myValue");
 env.remove("OTHERVAR");
 env.put("VAR2", env.get("VAR1") + "suffix");
 pb.directory(new File("myDir"));
 Process p = pb.start();