Calling bash script with redirection from Java
I have a bash shell script that executes a bunch of commands and redirects the command outputs to log files using >
. If I call the shell script from Java using Runtime.getRuntime().exec("sh shellscript.sh");
, the shell script gets executed but the log files don't get written! Why? And how do I make it work?
EDIT: Okay so what I'm trying to do is a little different. Your code works fine. But now redirection inside the Java program is not working. In the sample program below, the log file is not written!
$ cat 开发者_开发百科script.sh
#!/bin/sh
echo "Hello there"
echo "Hello there 2"
$ cat RunScript.java
public class RunScript {
public static void main(String[] argv) throws Exception {
int i = Runtime.getRuntime().exec("sh /home/gpx/script.sh >> log").waitFor();
System.out.println("Exit code : " + i);
}
}
The redirects that you are writing to - are they writing to absolute file paths or relative file pahts?
If its relative, then they would (probably) be relative to the work directory - so check that.
A SAMPLE TEST I DID THAT SHOWS ABSOLUTE PATHS WILL WORK
$ cat script.sh
#!/bin/sh
echo "Hello there"
echo "Hello there 2" >> /Users/madhurt/test/log
exit 2
$ cat RunScript.java
public class RunScript {
public static void main(String[] argv) throws Exception {
int i = Runtime.getRuntime().exec("sh /Users/madhurt/test/script.sh").waitFor();
System.out.println("Exit code : " + i);
}
}
$ pwd
/Users/madhurt/test
$ ls -lrt
total 24
-rwxr-xr-x 1 madhurt staff 87 Dec 6 18:28 script.sh
-rw-r--r-- 1 madhurt staff 214 Dec 6 18:32 RunScript.java
-rw-r--r-- 1 madhurt staff 907 Dec 6 18:32 RunScript.class
$ java RunScript
Exit code : 2
$ ls -lrt
total 32
-rwxr-xr-x 1 madhurt staff 87 Dec 6 18:28 script.sh
-rw-r--r-- 1 madhurt staff 214 Dec 6 18:32 RunScript.java
-rw-r--r-- 1 madhurt staff 907 Dec 6 18:32 RunScript.class
-rw-r--r-- 1 madhurt staff 14 Dec 6 18:33 log
$ cat log
Hello there 2
$
My Java-knowledge is scant, but it's my understanding that you have to write:
Runtime.getRuntime().exec("sh shellscript.sh").waitFor();
Check if you have write permissions to the path you are appending the log too. If you run this app within a container, it will most likely use that user's id. Try to write the file in /tmp/
and see if it appears there.
精彩评论