Search code examples
javashellexecute

How to execute an script from another path


I want to execute myscript.sh from a java project.
The call I want to do is something like this:

Process p = Runtime.getRuntime().exec("./myscript.sh "+param1+" "+param2);

The problem is that this script.sh is not in the same path, so I tryed to do:

Process p = Runtime.getRuntime().exec("src/main/resources/./myscript.sh "+param1+" "+param2);

But the script is not executed anymore. I guess the problem is in the way I put the path, because I have checked and the script works perfectly if it is in the same path.

Any ideas?

Thanks in advance


Solution

  • You could use the ProcessBuilder instead. In the documentation for Runtime.exec you can even read the following:

    ProcessBuilder.start() is now the preferred way to start a process with a modified environment.

    As an example shows in the documentation, you can use pb.directory(File f) to set the working directory:

    ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");
    // ...
    pb.directory("myDir");
    Process p = pb.start();