MonsterJava MonsterJava - 1 year ago 153
Bash Question

Get return code and status from bash script into Java file

I am working in JavaFX scene builder App where at some point my code flow execution is like below:

From my Java class a bash script script1 called
From

MyClass.java


exec(./Script1)


in
script1 an another script script2 called

called ./script2


script2 an another script script3 called

In
script3

if [ ! "$upgrade_file_path" = "" ]; then
echo "BUILD SUCCESS"
echo "upgrade.cpio.gz : "$upgrade_file_path
//LINE-1
else
echo "FAILED TO CREATE upgrade.cpio.gz"
fi


What I need :

LINE-1 : Can I return some exit code from here to my java file (MyClass.java), I need to show the BUILD SUCESS string along with
$upgrade_file_path
and an exit code in my javafx label.
Or I can save this exit code,path and status in a string in my
MyClass.java
file?

Update:

I am using an external jar to connect SSH. What I am trying to do is to connect a linux machine from my windows machine, and to achieve this I have used sshexec.jar https://code.google.com/p/sshxcute/downloads/list

where below code does the job of connecting and executing the bash script

ConnBean cb = new ConnBean(buildServerURL, buildServerUsername,buildServerPassword);
// Put the ConnBean instance as parameter for SSHExec static method getInstance(ConnBean) to retrieve a singleton SSHExec instance
ssh = SSHExec.getInstance(cb);
//Connect to server
ssh.connect();
CustomTask sampleTask = new ExecCommand("/usr/init/checkout.sh");
//Execution of main taks
Result rs = ssh.exec(sampleTask);

Answer Source

In order to execute shell command from java we need to use some library, in your case you are using SSHExec, in this jar you can have the result/exit code that is returned from the shell script.

if [ ! "$upgrade_file_path" = "" ]; then
    echo "BUILD SUCCESS"
    echo "upgrade.cpio.gz : "$upgrade_file_path
    //Here you can just add something like:
    exit 0;
else
    echo "FAILED TO CREATE upgrade.cpio.gz"
    exit 1;
fi

when the above scripts executes an exit code will be thrown from here and you can have this exit code in your java application something like this:

    ConnBean cb = new ConnBean(buildServerURL, buildServerUsername,buildServerPassword);
    // Put the ConnBean instance as parameter for SSHExec static method getInstance(ConnBean) to retrieve a singleton SSHExec instance
    ssh = SSHExec.getInstance(cb);          
    //Connect to server
    ssh.connect();
    CustomTask sampleTask = new ExecCommand("/usr/init/checkout.sh");
    //Execution of main taks
    Result rs = ssh.exec(sampleTask);
    int exitCode = rs.rc(); //rc stands for result code, and this rc will have what shell returned.
    if(exitCode!=0){
      //Error message
}else 
     //Success message.