CodeMed
CodeMed

Reputation: 9181

How do I return a boolean from a Java program to a CentOS shell script?

A shell script run on a CentOS 7 server needs to pass three parameters to a Java program, and then read a Boolean value returned by the Java program as a result of operations done on the three parameters. What specific changes do I need to make to the code below in order to return the Boolean value into the shell script?

Here is a first attempt at the shell script:

#!/bin/bash
ARG0=0
ARG1=0 
ARG2=0
CLASSPATH=/path/to/classes
echo -n "Enter zeroth arg: "
read ARG0
echo -n "Enter first arg: "
read ARG1
echo -n "Enter second arg: "
read ARG2
java -cp $CLASSPATH my.package.SomeClass[ARG0, ARG1, ARG2]
#How do I return the Boolean from the Java class into this shell script

Here is the Java class:

public class SomeClass {

private static Boolean passes = false;

public static void main(String[] args) {
    String arg0 = null;
    String arg1 = null;
    String arg2 = null;

    for (int i = 0; i < args.length; i++){
        if(i==0){arg0=args[i];}
        if(i==1){arg1=args[i];}
        if(i==2){arg2=args[i];}
    }
    
    if(!arg0.equals(null) && !arg1.equals(null) && !arg2.equals(null)){
        passes = doSomeTest(arg0, arg1, arg2);
    }
    else{passes = false;}
}

public static boolean doSomeTest(String arg0, String arg1, String arg2){
    if(passes_test){return true;}
    else{return false;}
}

public static boolean getPasses(){return passes;}

}

Upvotes: 2

Views: 360

Answers (2)

Jashaszun
Jashaszun

Reputation: 9270

You can use the System.exit(int) function to return a status code. This is done instead of main returning an int, as in C, C++, C#, etc.

Normally, 0 means success and anything else means failure.

Here, it looks like at the end of your main method you'll want to System.exit(passes ? 0 : 1);

In bash you can read the status code by using the $? variable. How you use it really depends on, well, how you use it later in your script. However, you don't need to change anything in the line that starts your Java program.

If you want a conditional based on the status code of your Java program, you can do the following after your java -cp ... call:

if [ $? -eq 0 ]
then
    abc
else
    xyz
fi

Upvotes: 2

Roberto Attias
Roberto Attias

Reputation: 1903

A java program can return a value by explicitly calling System.exit(ret_value), where ret_value is an integer. So, you could do this at the end of main:

int ret = passes ? 1 : 0;
System.exit(ret);

Upvotes: 1

Related Questions