You should really look at Process Builder. It is really built for this kind of thing.
ProcessBuilder pb = new ProcessBuilder("myshellScript.sh", "myArg1", "myArg2");
Map<String, String> env = pb.environment();
env.put("VAR1", "myValue");
env.remove("OTHERVAR");
env.put("VAR2", env.get("VAR1") + "suffix");
pb.directory(new File("myDir"));
Process p = pb.start();
Answer from Milhous on Stack OverflowVideos
You should really look at Process Builder. It is really built for this kind of thing.
ProcessBuilder pb = new ProcessBuilder("myshellScript.sh", "myArg1", "myArg2");
Map<String, String> env = pb.environment();
env.put("VAR1", "myValue");
env.remove("OTHERVAR");
env.put("VAR2", env.get("VAR1") + "suffix");
pb.directory(new File("myDir"));
Process p = pb.start();
You can use Apache Commons exec library also.
Example :
package testShellScript;
import java.io.IOException;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
public class TestScript {
int iExitValue;
String sCommandString;
public void runScript(String command){
sCommandString = command;
CommandLine oCmdLine = CommandLine.parse(sCommandString);
DefaultExecutor oDefaultExecutor = new DefaultExecutor();
oDefaultExecutor.setExitValue(0);
try {
iExitValue = oDefaultExecutor.execute(oCmdLine);
} catch (ExecuteException e) {
System.err.println("Execution failed.");
e.printStackTrace();
} catch (IOException e) {
System.err.println("permission denied.");
e.printStackTrace();
}
}
public static void main(String args[]){
TestScript testScript = new TestScript();
testScript.runScript("sh /root/Desktop/testScript.sh");
}
}
For further reference, An example is given on Apache Doc also.
You need Runtime.getRuntime().exec(...). See a very extensive example (don't forget to read the first three pages).
Keep in mind that Runtime.exec is not a shell; if you wish to execute a shell script your command line would look like
/bin/bash scriptname
That is, the shell binary you need is fully qualified (although I suspect that /bin is always in the path). You can not assume that if
myshell> foo.sh
runs,
Runtime.getRuntime.exec("foo.sh");
also runs as you are already in a running shell in the first example, but not in the Runtime.exec.
A tested example (Works on My Linux Machine(TM)), mosly cut-and-past from the previously mentioned article:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class ShellScriptExecutor {
static class StreamGobbler extends Thread {
InputStream is;
String type;
StreamGobbler(InputStream is, String type) {
this.is = is;
this.type = type;
}
public void run() {
try {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null)
System.out.println(type + ">" + line);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("USAGE: java ShellScriptExecutor script");
System.exit(1);
}
try {
String osName = System.getProperty("os.name");
String[] cmd = new String[2];
cmd[0] = "/bin/sh"; // should exist on all POSIX systems
cmd[1] = args[0];
Runtime rt = Runtime.getRuntime();
System.out.println("Execing " + cmd[0] + " " + cmd[1] );
Process proc = rt.exec(cmd);
// any error message?
StreamGobbler errorGobbler = new StreamGobbler(proc
.getErrorStream(), "ERROR");
// any output?
StreamGobbler outputGobbler = new StreamGobbler(proc
.getInputStream(), "OUTPUT");
// kick them off
errorGobbler.start();
outputGobbler.start();
// any error???
int exitVal = proc.waitFor();
System.out.println("ExitValue: " + exitVal);
} catch (Throwable t) {
t.printStackTrace();
}
}
}
Shell Script test.sh code
#!/bin/sh
echo "good"
Java Code to execute shell script test.sh
try {
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(new String[]{"/bin/sh", "./test.sh"});
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "";
while ((line = input.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
System.out.println(e.toString());
e.printStackTrace();
}
create a file named "sync" in /usr/bin containing the following:
java -jar {PATH TO JARFILE} $1 $2
Replace {PATH TO JARFILE} with the path to the jarfile
Make the file executable by typing chmod +x sync while in /usr/bin
you can create a shell with name say "run.sh" (note .sh extension which tell it is a shell script) and copy it in /usr/local/bin directory.
1.Script (run.sh)
#!/bin/sh
arg1=$1
arg2=$2
##directory where jar file is located
dir=/directory-path/to/jar-file/
##jar file name
jar_name=json-simple-1.1.1.jar
## Permform some validation on input arguments, one example below
if [ -z "$1" ] || [ -z "$2" ]; then
echo "Missing arguments, exiting.."
echo "Usage : $0 arg1 arg2"
exit 1
fi
java -jar $dir/$jar_name arg1 arg2
copy the script in /usr/local/bin
cp run.sh /usr/local/bin
Give execute permission to the script
chmod u+x /usr/local/bin/test.sh
now you can type just word run or run.sh on command line : shell will auto-complete the script name and also it can executed by pressing enter key.