How can I call a shell script through java code?
I have writtent the below code.
I am getting the process exit code as 127.
But it seems my shell script in unix machine is never called.
String scriptName = "/xyz/downloads/Report/Mail.sh";
String[] commands = {scriptName,emailid,subject,body};
Runtime rt = Runtime.getRuntime();
Process process = null;
try{
process = rt.exec(commands);
process.waitFor();
int x = process.exitValue();
System.out.println("exitCode "+x);
}catch(Exception e){
e.printStackTrace();
}
From this post here 127 Return code from $?
You get the error code if a command is not found within the PATH or the script has no +x mode.
You can have the code below to print out the exact output
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
String s= null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
BufferedReader stdOut = new BufferedReader(new InputStreamReader(process. getErrorStream()));
String s= null;
while ((s = stdOut.readLine()) != null) {
System.out.println(s);
}
If you are getting an exit code, then your script is executed. There is a command that you are running inside of "Mail.sh", which is not succeccfully executed and returning a status code of 127.
There could be some paths that are explicitly set in your shell, but is not available to the script, when executed outside of the shell.
Try this...
Check if you are able to run /xyz/downloads/Report/Mail.sh in a shell terminal. Fix the errors if you have any.
If there are no errors when you run this in a terminal, then try running the command using a shell in your java program.
String[] commands = {"/bin/sh", "-c", scriptName,emailid,subject,body};
(Check #John Muiruri's answer to get the complete output of your command. You can see where exactly your script is failing, if you add those lines of code)
Related
I had question about running scripts using Junit 5. I have the following piece of code:
public class RunMvnSubprocess {
#Test
public void main() throws IOException, InterruptedException {
String[] cmd = new String[]{"mvn.cmd", "-version"}; // command to be executed on command prompt.
Process p = Runtime.getRuntime().exec(cmd);
try (BufferedReader output = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
String line;
while ((line = output.readLine()) != null) {
System.out.println(line);
}
}
p.waitFor();
}
}
I get no output when I run it using Junit 5.7.0. However, running this on Junit 4.13.2 works fine.
Please note that I am running this piece of test in Windows 10 Pro version 21H1.
EDIT:
Modifying
new String[]{"mvn.cmd", "-version"}
to
new String[]{"cmd", "/c", "\"mvn -version\""}
works for me, but launching a subshell is a bad practice so I am keeping this workaround as a last resort.
Note that you are implicity running a sub-shell as the Windows command CMD.EXE is called to interpret the contents of mvn.cmd, so your value of cmd is equivalent to:
cmd = new String[]{ "cmd", "/c", "call mvn.cmd -version"};
If you get no error code from waitFor or no output or no exception, then the issue will be reported in the STDERR stream. Change to use ProcessBuilder instead and you can merge STDERR to STDOUT as follows:
ProcessBuilder pb = new ProcessBuilder(cmd);
// No STDERR => merge to STDOUT
pb.redirectErrorStream(true);
Process p = pb.start();
Also, no need to write much code to consume STDOUT:
try(var stdo = p.getInputStream()) {
stdo.transferTo(System.out);
}
int rc = p.waitFor();
if (rc != 0) throw new RuntimeException("test failed");
Hopefully this will explain your problem with the mvn command.
I am writing a java program that needs to execute shell commands, so I wrote a function that would take the command to execute as a string (ie: "mkdir ~/Folder1") and execute that command with the shell. Here is the function:
private static void shell(String cmd)
{
try
{
Runtime run = Runtime.getRuntime();
Process pr = run.exec(cmd);
pr.waitFor();
BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "";
while ((line = buf.readLine()) != null) {
System.err.println(line); // show any errors returned by the command executed on the error console
}
} catch (Exception ee) {}
}
for some weird reason this function is not executing any commands. Did I do this wrong? It seems like a simple thing to execute shell commands, but it is not working.
I think you are passing the command string as some mkdir command like ,
"mkdir C:\some\folder\path".
mkdir is not some binary in Windows path, it's a parameter to command line.
Use the command string as "cmd.exe /c mkdir C:\some\folder\path"
Then it should work fine.
I am trying to write a java GUI in netbeans for executing a program on the command line, and currently have this piece of code assigned to a button
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try
{
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("open -a /Applications/Utilities/Terminal.app");
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line=null;
while((line=input.readLine()) != null)
{
System.out.println(line);
}
int exitVal = pr.waitFor();
System.out.println("Exited with error code "+exitVal);
}
catch(Exception e)
{
System.out.println(e.toString());
e.printStackTrace();
}
}
This opens the terminal, however I would like to know how I should go about inputting commands into the terminal while still just pressing the button (ex: "ls", "cd", "javac" etc) Thanks!
UPDATE:
#Codebender My code now looks like this.
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("open -a /Applications/Utilities/Terminal.app");
new PrintStream(pr.getOutputStream).println("ls");
I am getting the error "cannot find symbol, symbol: variable getOutputStream, location: variable pr of type process" and a red line under getOutputStream. Any ideas?
#Codebender So should it be like this?
new PrintStream(pr.getOutputStream{println("ls")});
Use can use outputStream to write to the terminal. Wrap it up with a printstream to make things easier.
Process pr = rt.exec("open -a /Applications/Utilities/Terminal.app");
PrintStream ps = new PrintStream(pr.getOutputStream());
ps.println("ls" + System.lineSeparator());
// Follow with the reading of output from terminal.
If your Terminal.app is the default linux terminal, instead of opening a new one you can try,
Process pr = rt.exec("ls");
// Follow with the reading of output.
Just found this post (and found the code which I'm also pasting below):
java runtime.getruntime() getting output from executing a command line program
My question is, how do I kill the process? It seems that the code blocks in the while loop. I've tried several options like using a boolean, running all the code in a separate thread and stuff like this, but without any success.
I just want to start an Android emulator and kill it whenever I want.
Runtime rt = Runtime.getRuntime();
String[] commands = {"emulator", "-avd", "jenkins",
"-scale", "96dpi", "-dpi-device", "100"};
Process proc = rt.exec(commands);
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(proc.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
Okay.
Use below code to get The Process ID of that current running thread or Process.
String processName =java.lang.management.ManagementFactory.getRuntimeMXBean().getName();
String ProcessID = processName.split("#")[0];//Process Id
Use that Process ID to kill that Process in your CPU.
I think for that purpose you may wish to write any other trigger or any condition in While loop.
I am trying to execute a shell script with command line arguments using ProcessBuilder, this shell script inturn calls two other shell scripts that uses this argument. The first shell script runs fine, but when the second one is started it returns exit code 1.
ProcessBuilder snippet from Java Program:
//scenario - A string that holds a numerical value like 1 or 2 etc
String[] command2 = {"/bin/bash", "<path to shell script>/runTemporaryTestSuite.sh", scenario};
ProcessBuilder pb2 = new ProcessBuilder(command2);
Process p2 = pb2.start();
BufferedReader br = new BufferedReader(new InputStreamReader(p2.getInputStream()));
String line;
//print - is an object ref of response.getWriter() //
print.println("Output of running "+Arrays.toString(command2)+" is: ");
while ((line = br.readLine()) != null) {
print.println(line);
}
try {
int exitValue = p2.waitFor();
print.println("<br><br>Exit Value of p2 is " + exitValue);
} catch (InterruptedException e) {
e.printStackTrace();
}
runTemporaryTestSuite.sh
#!/bin/bash
sh <path to script>/clearRegressionResult.sh (This runs fine)
sh <path to script>/startRegression.sh $1 (This is where the issue occurs)
startRegression.sh looks like:
SUITE_PATH="./"
java -DconfigPath=${SUITE_PATH}/config.xml -Dscenario=$1 -Dauto=true -jar test.jar
My output:
Output of running [/bin/bash, /runTemporaryTestSuite.sh, 29] is:
Exit Value of p2 is 1
Any help in resolving this is really appreciated.
In think the problem is not that you cannot launch shell script with arguments, I was curious and I did a test
public class Main {
public static void main(String[] args) throws IOException {
String[] command = {"/bin/bash", "test.sh", "Argument1"};
ProcessBuilder p = new ProcessBuilder(command);
Process p2 = p.start();
BufferedReader br = new BufferedReader(new InputStreamReader(p2.getInputStream()));
String line;
System.out.println("Output of running " + command + " is: ");
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
here is the test.sh script
echo Hello im the script, here your args $#
Here the output
Output of running [Ljava.lang.String;#604e9f7f is:
Hello im the script, here your args Argument1
What I think is just that your startRegression.sh exit with a non-0 status (aka it failed somewhere) and it have repercussion, runTemporaryTestSuite.sh will also exit with a non-zero status, and so on hence the message : Exit Value of p2 is 1
What I see right now,
SUITE_PATH="./"
java -DconfigPath=${SUITE_PATH}/config.xml [..] the configPath will be .//config.xml so maybe you have a plain file not found issue? I might be wrong, hope it helped