The simplest solution would be to have your application extract the shell script into a temporary location and execute it from there.
You can produce a temporary file in Java by calling File.createTempFile(String, String).
Another thing that you could possibly do is pass the contents of the script, as loaded from your jar, as the standard input of the shell.
As a simplification, if I had an archive a.zip
containing a script a.sh
, this would execute it:
$ unzip -p a.zip a.sh | bash
From a Java program, you could do the following:
import java.io.*;
class Test{
public static void main(String[]args) throws Exception {
StringBuilder sb = new StringBuilder();
// You're not strictly speaking executing a shell script but
// rather programatically typing commands into the shell
// sb.append("#!/bin/bash\n");
sb.append("echo Hello world!\n");
sb.append("cd /tmp\n");
sb.append("echo current directory: `pwd`\n");
// Start the shell
ProcessBuilder pb = new ProcessBuilder("/bin/bash");
Process bash = pb.start();
// Pass commands to the shell
PrintStream ps = new PrintStream(bash.getOutputStream());
ps.println(sb);
ps.close();
// Get an InputStream for the stdout of the shell
BufferedReader br = new BufferedReader(
new InputStreamReader(bash.getInputStream()));
// Retrieve and print output
String line;
while (null != (line = br.readLine())) {
System.out.println("> "+line);
}
br.close();
// Make sure the shell has terminated, print out exit value
System.out.println("Exit code: " + bash.waitFor());
}
}