2

I need to execute linux commands from JSP. It is working fine. But i need to start some sh file in a particular directory in linux through JSP. say /home/username/something/start.sh

try{
String command= "cd /home/username/something";

Runtime.getRuntime().exec(command);
Runtime.getRuntime().exec("./start.sh")


out.println("Child");
}
catch(Exception e)
{ out.println("Error");
}

It says FIle or Directory not found.

I tried Runtime.getRuntime().exec("pwd"), It is showing something like "java.lang.UNIXProcess@fc9d2b" !! :O

I need to change the pwd and execute some commands through jsp. How can i do that?? Any help would be appreciated.

BinaryMee
  • 2,102
  • 5
  • 27
  • 46
  • That `java.lang.UNIXProcess@fc9d2b` String you're getting is the `toString()` of the `Process` instance `exec()` is returning. In order to see the output of the command, you should [capture the standard output of the `Process`](http://stackoverflow.com/q/882772/851811). – Xavi López Mar 12 '13 at 12:47
  • Can you plz tell how to capture standard output of the `Process` ?? – BinaryMee Mar 12 '13 at 12:49
  • Use [`Process.getOutputStream()`](http://docs.oracle.com/javase/6/docs/api/java/lang/Process.html#getOutputStream()). – Xavi López Mar 12 '13 at 12:49

1 Answers1

7

You shouldn't (and actually, it seems you can't) set a working directory like that. Each Process object given by Runtime.exec() will have its own working directory.

As answered in How to use “cd” command using java runtime?, you should be using the three argument version of Runtime.exec(), in which you provide a File that will be the working directory. From its javadoc:

Executes the specified command and arguments in a separate process with the specified environment and working directory.

Or even better, use ProcessBuilder along with ProcessBuilder.directory() instead:

ProcessBuilder pb = new ProcessBuilder("start.sh");
pb.directory(new File("/home/username/something"));
Process p = pb.start();
Community
  • 1
  • 1
Xavi López
  • 27,550
  • 11
  • 97
  • 161