Question

I have a sh file which conatins a many sudo commands, say a script as below:

test.sh

#!/bin/sh
sudo apt-get install gedit
sudo date --set="2014/02/20 10:00"

When I execute the test.sh from terminal it works fine. Problem is when I try to execute this file from a java class. The script doesn't execute. I tried this:

Process proc = Runtime.getRuntime().exec("/bin/sh","/home/priyatam/test.sh");

Does anyone have an idea to execute this sudo command from java class? Please share.

Was it helpful?

Solution

well as the script will be outputting the prompt to the screen, it will be necessary to capture the processes inputstream

InputStream stdout = process.getInputStream ();

I would also recommend using

ProcessBuilder builder = new ProcessBuilder("/home/user/test.sh");
builder.redirectErrorStream(true);
Process process = builder.start();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top