0

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

toolkit
  • 49,809
  • 17
  • 109
  • 135

5 Answers5

5

Have a look at ProcessBuilder - example here.

ChristopheD
  • 112,638
  • 29
  • 165
  • 179
2

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
  • 391,730
  • 64
  • 469
  • 606
1

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
  • 30,779
  • 11
  • 72
  • 106
0

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.

Community
  • 1
  • 1
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
0

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

java shell for executing/coordinating processes?

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();
    }
Community
  • 1
  • 1
Benj
  • 31,668
  • 17
  • 78
  • 127