tags:

views:

111

answers:

5

Hi! I want to send a command to linux shell and get it's response with java.How can i do this?

+2  A: 

You should look at the Runtime class, and its exec() family of methods.

It's probably best to explicitly specify that you want to run the command through a shell, i.e. create a command line like "bash -c 'my command'".

unwind
-1 Don't use Runtime, just ProcessBuilder.
Aaron Digulla
@Aaron Digulla: Could you expand on why is that?
Alberto Zaccagni
@Montecristo: see http://java.sun.com/developer/JDCTechTips/2005/tt0727.html#2
ChristopheD
+1  A: 

Execute a process like this

Runtime.getRuntime().exec("ls");

...then you could get the process input stream and read it with a Reader to get the response

Alberto Zaccagni
+5  A: 

Have a look at ProcessBuilder - example here.

ChristopheD
Or search this site for "java processbuilder"
Aaron Digulla
A: 

See the Runtime class and the exec() method.

Note that you need to consume the process's stdout/sterr concurrently, otheriwse you'll get peculiar blocking behaviour. See this answer for more information.

Brian Agnew
A: 

I wrote a little class to do this in a very similar question a couple of weeks ago:

http://stackoverflow.com/questions/1596396/java-shell-for-executing-coordinating-processes/1596842#1596842

The class basically let's you do:

    ShellExecutor excutor = new ShellExecutor("/bin/bash", "-s");
    try {
            System.out.println(excutor.execute("ls / | sort -r"));
    } catch (IOException e) {
            e.printStackTrace();
    }
Benj