7

How do I execute Bash commands and collect the output from Java?

Hi all, basically I am writing a basic console app, and would like to be able to run commands from it, such as sudo***, halt, ifconfig, etc.

Any insight?.

2 Answers 2

12

You can use processBuilder API for this purpose. See this example.

Sign up to request clarification or add additional context in comments.

4 Comments

don't forget to call processBuilder.redirectErrorStream(true). Or spin up another thread to drain stderr.
I don't see any mention of bash in the "example"
Link to example broken.
Do you have another example link? or a mirror?
3

untested code:

Runtime run = Runtime.getRuntime();
Process pr = run.exec(bashcommand);
pr.waitFor();
BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.