PDA

View Full Version : Java execute shell commands?



aktiwers
January 29th, 2008, 05:20 PM
What is the simplest way I could run bash scripts or shell commands using Java?

I tried with exec, but it wont even accept the 'cd' command..

Anyone know a simple way to do this? If I could just get it to run a bash script, I could put all my commands in there.

Thanks

popch
January 29th, 2008, 05:23 PM
At a guess I would think that you execute the program 'bash' from java and pass it the commands you want executed in a file or pipe.

a9bejo
January 29th, 2008, 08:31 PM
cd is not a separate program like ls or wc, but a command directly build into many command like interpreter (like bash).

So Runtime#exec is the way to go, but you cannot change the working directory of the java process this way. What you can do is to use Runtime#exec to call a script that opens a shell and then execute a set of commands in that shell, including cd.

kozmo
September 24th, 2008, 11:25 PM
import java.lang.* ;

public class MyJavaClass
{
public void runCmd(String[] args)
{
String cmd = "/home_dir/./my_shell_script.sh" ;
Runtime run = Runtime.getRuntime() ;
Process pr = run.exec(cmd) ;
pr.waitFor() ;
BufferedReader buf = new BufferedReader( new InputStreamReader( pr.getInputStream() ) ) ;

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

}

}

tinny
September 25th, 2008, 05:21 AM
Here is some code that does what you want

http://ubuntuforums.org/showpost.php?p=5409831&postcount=19

jespdj
September 25th, 2008, 09:19 AM
A more flexible way than Runtime.exec(...) to do this is to use the class java.lang.ProcessBuilder. Look it up in the Java API documentation.

*edit* Oh wait, who are we fooling? This is a 9 month old thread...

tinny
September 25th, 2008, 10:56 AM
A more flexible way than Runtime.exec(...) to do this is to use the class java.lang.ProcessBuilder. Look it up in the Java API documentation.

*edit* Oh wait, who are we fooling? This is a 9 month old thread...

:lolflag:

oops

hoboy
September 25th, 2008, 12:35 PM
Try this link maybe
http://www.beanshell.org/docs.html