Java code to launch shell script with arguments

Java code to launch shell script with arguments

To launch a shell script with arguments in Java, you can use the Runtime and Process classes to execute the script as an external process.

Here is an example of how to launch a shell script with arguments in Java:

import java.io.IOException;

public class Main {
  public static void main(String[] args) {
    String script = "/path/to/script.sh";
    String[] scriptArgs = {"arg1", "arg2", "arg3"};

    try {
      Process process = new ProcessBuilder(script, scriptArgs).start();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
Source:w‮ual.ww‬tturi.com

In this example, the ProcessBuilder class is used to create a new process that executes the script.sh script with the specified scriptArgs arguments. The start method is then called to start the process.

Keep in mind that this approach requires that the script have execute permissions and be located in a directory that is included in the PATH environment variable.

Alternatively, you can use the Runtime class to execute the script as an external process:

import java.io.IOException;

public class Main {
  public static void main(String[] args) {
    String script = "/path/to/script.sh";
    String[] scriptArgs = {"arg1", "arg2", "arg3"};

    try {
      Runtime runtime = Runtime.getRuntime();
      runtime.exec(new String[] {script, scriptArgs[0], scriptArgs[1], scriptArgs[2]});
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

In this example, the exec method of the Runtime class is used to execute the script.sh script with the specified scriptArgs arguments.

Created Time:2017-11-03 00:14:41  Author:lautturi