I want to execute a shell command via Java and tried using ProcessBuilder.class and Process.class:
public Process createProcess() throws IOException
{
List<String> cmds = new ArrayList<>();
cmds.add("start_date=\"2021-07-04\" && echo \"Starting with startdate=$start_date\"");
return (new ProcessBuilder(cmds)).start();
}
When I execute the exact same command on my shell, it works. When I do this in Java I get:
java.io.IOException: Cannot run program "start_date="2021-06-10" (shorted ...)": error=2, No such file or directory
(I also tried it without the variable start_date by entering the date directly)
Why won't it work? Can I configure somehow, that Java knows that this is not a file etc.?
you can write script in separate .sh file and pass the path of file and any parameter that is need for script execution ( here you may need to pass startDate)
Then you can execute it as below as below
String[] cmd = {"sh","-c",pathOfShellScript+" "+ startDate};
ProcessBuilder pb = new ProcessBuilder();
pb.command(cmd);
Process proc = pb.start();