Reputation: 21
try{
//String[] cmd = new String[]{"/bin/sh", "send.sh"};
//Process pr = Runtime.getRuntime().exec(cmd); //nothing happens
//Process p = Runtime.getRuntime().exec("send.sh"); //File not found
//Process p = Runtime.getRuntime().exec("bash send.sh"); //nothing happens
// ProcessBuilder pb = new ProcessBuilder("bash","send.sh");
// Process p = pb.start(); //nothing happens
}
catch(Throwable t)
{
t.printStackTrace();
}
With this code I am trying to start a simple bash file which is located in the directory of the program. The code of the bash file works when I start it with shell or by simply executing it. The code of the bash file works.
I've tried every option but they are all not working. I've commented what happens in each case. I don't understand that it don't find the file because the bash file is located in the same directory.
Upvotes: 1
Views: 1987
Reputation: 33422
You don't see an output for two reasons:
And, probably, you need to use a command like /bin/bash -c path/to/your/file.sh
. Note that -c
flag.
IMHO, the best way to craft and execute external processes in Java is java.lang.ProcessBuilder
.
Supposing that you have your sh
file somewhere the in resources
directory, here is an example main class:
public class App {
public static void main(String[] args) throws Exception {
final ProcessBuilder processBuilder = new ProcessBuilder("/bin/bash", "-c", App.class.getResource("/46964369.sh").getPath());
processBuilder.redirectInput(Redirect.INHERIT);
processBuilder.redirectOutput(Redirect.INHERIT);
processBuilder.redirectError(Redirect.INHERIT);
processBuilder.start().waitFor();
}
}
Note that I redirect process's streams with redirect*
methods. Redirect.INHERIT
redirects stream to the corresponding stream of the JVM instance. It works both for input and output streams. Finally, I am waiting for a process to finish with waitFor()
method. In fact, you can do more, like capturing the output into a string, providing input from a string or running the process asynchronously, but this is a minimal example.
If you store your sh
file in another place, you must update path-related logic.
Take a look at the complete example here. It's a Gradle project, and you can use ./gradlew run
to execute it:
$ ./gradlew run
:compileJava
:processResources
:classes
:run
Hello, world!
BUILD SUCCESSFUL in 4s
3 actionable tasks: 3 executed
Upvotes: 4