I was trying to execute shell scripts using java code. The following is a sample code to demonstrate the issue :
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command("/home/otaku/Programming/data/test1.sh");
try {
Process process = processBuilder.start();
StringBuilder output = new StringBuilder();
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
int exitVal = process.waitFor();
if (exitVal == 0) {
System.out.println(output);
} else {
System.out.println("Script exited abnormally");
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
The shell script file test1.sh that I am trying to execute :
#!/bin/bash
mkdir -p -- teeh
echo 'Succesfully executed script'
I am getting echo message and was able to print in the java console indicating that the shell script is executed successfully. But no directory is being created even though the command mkdir -p -- teeh is executed. If I manually execute the script file using terminal it works like a charm. I would like to know the reason behind this and a possible solution to this as well.
pwdto your shell script or aSystem.out.println(System.getProperty("user.dir"));to your Java class to make sure you're actually looking at the correct location. You shouldn't expect theteehdirectory to be created inside/home/otaku/Programming/data/if you're not calling the java script from that location for instance.