Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the bash command exit code from a Process run from within Java?

I have a program which is:

import java.io.*;
   import java.util.*;

   public class ExecBashCommand {
     public static void main(String args[]) throws IOException {

       if (args.length <= 0) {
         System.err.println("Need command to run");
         System.exit(-1);
       }

       Runtime runtime = Runtime.getRuntime();
       Process process = runtime.exec("./nv0914 < nv0914.challenge");
       Process process1 = runtime.exec("echo ${?}");
       InputStream is = process1.getInputStream();
       InputStreamReader isr = new InputStreamReader(is);
       BufferedReader br = new BufferedReader(isr);
       String line;

       //System.out.printf("Output of running %s is:", Arrays.toString(args));

       while ((line = br.readLine()) != null) {
         System.out.println(line);
       }

     }
    } 

note: nv0914 is a bash executable file and nv0914.challenge is a text file. When i run any normal command in terminal and just after that if I check the exit code using echo ${?}. Now I want to do the same by using a program, but the program is simply giving the output ${?}. Please help me out!

like image 683
Maverick Avatar asked May 04 '11 16:05

Maverick


People also ask

How do I get an exit code in bash?

To check the exit code we can simply print the $? special variable in bash. This variable will print the exit code of the last run command.

What command should I use to display the exit code of the previous command?

The echo command is used to display the exit code for the last executed Fault Management command.


1 Answers

Process.waitFor() returns an int That is where the exit code is returned. If you start an unrelated program, won't have a previous exit code which is why it doesn't return anything useful.

You can't use exitValue() reliably because you could call it before the program has finished. You should only call it after calling waitFor() (and it will give the same exit code waitFor() does)

From the Javadoc for exitValue

Throws: IllegalThreadStateException - if the subprocess represented by this Process object has not yet terminated.

like image 54
Peter Lawrey Avatar answered Sep 18 '22 12:09

Peter Lawrey