Omar Amr
Omar Amr

Reputation: 385

run a .sh file using java

I want to run a .sh file using java. I want a terminal to be opened and then I can execute another commands in the same terminal and finally destroy it. I already used ProcessBuilder but I could not accomplish this. My piece of code:

ProcessBuilder pb = new ProcessBuilder("/home/omar/ros_ws/baxter2.sh");
Process p = pb.start();

This method used to work in another code, but I don't know why it's not working in mine.

Thanks in advance

Upvotes: 1

Views: 4853

Answers (3)

Ali Seyedi
Ali Seyedi

Reputation: 1817

How do you know that it doesn't execute? Maybe you just aren't seeing its result. You should get p.getInputStream() after executing and print in your console, like:

BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null)
{
   System.out.println(line);
}

Also if you're using jdk 7+, try:

pb.redirectOutput(Redirect.INHERIT);
pb.redirectError(Redirect.INHERIT);
Process p = pb.start();

Upvotes: 1

Farag Zakaria
Farag Zakaria

Reputation: 198

I think you should grant the .sh file the executable permission to the OS user used to run the java program by using the below command.

chmod u+x baxter2.sh

Upvotes: 0

g101
g101

Reputation: 79

Does your program output an error, or is your program not interacting with the file?

I would suggest trying the directory method within ProcessBuilder.

Process p = null;
ProcessBuilder pb = new ProcessBuilder("baxter2.sh");
pb.directory("/home/omar/ros_ws");
p = pb.start();

If this doesn't work, you should also look into user permissions for the file that you're trying to access.

Upvotes: 1

Related Questions