user3545586 user3545586 - 7 months ago 45
Bash Question

run a .sh script from its own root using java

I have a shell script in a different directory than my java files. This script contains only

ls
which prints the files in the current directory. When I run the java project it prints the files in the root of the java project not the root of shell script. I want it to print the files in the root of the shell script.

Java code:

ProcessBuilder pb = new ProcessBuilder("/home/omar/ros_ws/baxter3.sh");
Process p = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}

Answer

Use the ProcessBuilder.directory, you probably want

String path = "/home/omar/ros_ws/baxter3.sh";
ProcessBuilder pb = new ProcessBuilder(path);
pb.directory(new File(path).getParent());