You should use the returned Process to get the result.
Runtime#exec executes the command as a separate process and returns an object of type Process. You should call Process#waitFor so that your program waits until the new process finishes. Then, you can invoke Process.html#getOutputStream() on the returned Process object to inspect the output of the executed command.
An alternative way of creating a process is to use ProcessBuilder.
Process p = new ProcessBuilder("myCommand", "myArg").start();
With a ProcessBuilder, you list the arguments of the command as separate arguments.
See Difference between ProcessBuilder and Runtime.exec() and ProcessBuilder vs Runtime.exec() to learn more about the differences between Runtime#exec and ProcessBuilder#start.
You should use the returned Process to get the result.
Runtime#exec executes the command as a separate process and returns an object of type Process. You should call Process#waitFor so that your program waits until the new process finishes. Then, you can invoke Process.html#getOutputStream() on the returned Process object to inspect the output of the executed command.
An alternative way of creating a process is to use ProcessBuilder.
Process p = new ProcessBuilder("myCommand", "myArg").start();
With a ProcessBuilder, you list the arguments of the command as separate arguments.
See Difference between ProcessBuilder and Runtime.exec() and ProcessBuilder vs Runtime.exec() to learn more about the differences between Runtime#exec and ProcessBuilder#start.
When you execute a script from Java it spawns a new shell where the PATH environment variable is not set.
Setting the PATH env variable using the below code should run your script.
String[] env = {"PATH=/bin:/usr/bin/"};
String cmd = "you complete shell command"; //e.g test.sh -dparam1 -oout.txt
Process process = Runtime.getRuntime().exec(cmd, env);
Videos
This should do it.
Copy#!/bin/bash
files="$@"
for i in $files;
do
echo "Doing $i"
java -jar somefile.jar <<< "$i"
done
Make sure you chmod u+x filename it first. Then call it like this:
Copy./filename firstfile secondfile thirdfile etc.
Other:
As sjsam pointed out, the use of <<< is a strictly bash thing. You are apparently using bash ("I'm rank new to bash..."), but if you weren't, this would not work.
Suppose my java program is HelloWorld.java. We can run it in 2 ways:
1st using executable jar
2nd by running java class from terminal
create a new text file and name it hello.sh
In hello.sh
Copy!/bin/bash
clear
java -jar HelloWorld.jar
Save it and open terminal:
1 navigate to directory where your HelloWorld.jar is present
2 give permission to terminal to run the bash script by using the following command
Copysudo chmod 754 hello.sh
3 run you script by running the following command
Copy./hello.sh
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.
Another way of doing would be to use Runtime.getRuntime(). Something like this
public void executeScript() throws IOException, InterruptedException {
Process p = Runtime.getRuntime().exec("sh /root/Desktop/chat/script.sh");
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader errorReader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String line = "";
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
line = "";
while ((line = errorReader.readLine()) != null) {
System.out.println(line);
}
}
With the above test you can not guaranty that whether it is running or not. Because clearly you told that your are running a infinite loop inside your second java application. Now my advise would be to put some System.out.println statement inside that infinite loop and use below java code to execute your shell script. Here in the output.txt file you can see the output from your shell script as well as java program and you will know whether application executed successfully or not. Also put some echo statement inside your shell script as well.
String[] command ={"/root/Desktop/chat/script.sh", "command line param if any"};
ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectOutput(new File("/tmp/output.txt"));
String result;
String overall="";
try {
Process p = pb.start();
p.waitFor();
BufferedReader br = new BufferedReader(
new InputStreamReader(p.getInputStream()));
while ((result = br.readLine()) != null){
overall = overall + "\n" + result;
}
p.destroy();
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
If the problem is that running the script doesn't show a terminal window, the solution depends on the window manager you're using. Gnome as well as KDE allow to edit properties of desktop shortcuts on a right-click and setting a option like "run in terminal" there.
Another way is to edit the desktop configuration file manually: you can find them in the Desktop subdirectory of your home dir. Just add a line with Terminal=true to the desktop configuration file that should run the server.
Why are you using echo? That just prints the rest of the line as a sequence of literals to the terminal.
java.io.IOException: Cannot run program "./path/to/bash": error=2, No such file or direct
It mean path of file was wrong. Please check file path again. What folder contains this file?
Recently I used the below approach to execute a bash script.
Process exec = getRuntime().exec("/home/user/test/test.sh");
java.util.Scanner s = new java.util.Scanner(exec.getInputStream()).useDelimiter("\\A");
System.out.println(s.next());
Whenever I tried getRuntime().exec("./home/user/test/test"); I got the exact error you were getting. java.io.IOException: Cannot run program "./home/user/test/test": error=2, No such file or directory.
To execute any command from any directory, please follow the below approach.
String []command ={"/bin/bash","-c", "ls"};
Process exec = getRuntime().exec(command,null,new
File("/home/user/test"));
java.util.Scanner s = new java.util.Scanner(exec.getInputStream()).useDelimiter("\\A");
System.out.println(s.next());
Hope this is some way helpful.