Your code is right and I am sure you are not getting exceptions, if you read using proc.getErrorStream()
you will not get anything.
Commands 100% get executed that way, having said that now thing is that you are echo'ing something and you need to read it back using BufferedReader
.
Check below example which will successfully create a directory called "stackOverflow" and print what you are echo'ing. For the putting it into a log file I am afraid that you can do it using ">", you may have to use some editor command or create file using Java.
Bottom line: Runtime.getRuntime().exec("command")
is the correct and defined way to execute Unix commands or scripts from Java and it WORKS.
test.sh
#!/bin/bash
echo "hola"
mkdir stackOverflow
Test.java
import java.io.*;
public class Test {
public static void main(String[] args) throws Exception {
try {
String target = new String("/home/hagrawal/test.sh");
// String target = new String("mkdir stackOver");
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(target);
proc.waitFor();
StringBuffer output = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
System.out.println("### " + output);
} catch (Throwable t) {
t.printStackTrace();
}
}
}