How to run Unix shell script from Java code?

Vicky picture Vicky · Feb 8, 2009 · Viewed 397.1k times · Source

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

Runtime.getRuntime().exec(myCommand);

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?

Answer

Milhous picture Milhous · Feb 8, 2009

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();