How to run Unix shell script in a java code using ExpectJ tool?

2k views Asked by At

This is my hello.sh shell script

VALID_NAME="abcd"

echo "Name: "

read name

if [ "$name" == $VALID_NAME ]; then

echo "correct"

else

echo "unexpected input"

fi

========================================================

This is my Java code

import java.io.IOException;

import expectj.*;

public class Trial {
public static void main(String[] args) {

    ExpectJ exp = new ExpectJ();
    String command = "sh /root/Desktop/hello.sh";
    Spawn s;
    try {
        s = exp.spawn(command);
        s.expect("Name: ");
        s.send("abcd");
        System.out.println(s.getCurrentStandardOutContents());
        s.stop();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TimeoutException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }catch (ExpectJException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }       
}
}

======================================================================

And this is my OUTPUT

Name: //this is wat it asks for

abcd //this is what i give..and nothing happens

============================================================

I've corrected my java code above..

2

There are 2 answers

4
AVH On BEST ANSWER

In your Java code you look for

s.expect("VALID_NAME=");

yet in your Bash code, you have:

echo "Name: "

It seems like simply changing your Java code to the following should work:

s.expect("Name: ");
4
DaveH On

I've never used ExpectJ, but the start of your error messagesh: hello.sh: No such file or directory suggests that it is unable to find your shell script. Have you tried it with the full path to the script?

String command = "sh /root/Desktop/hello.sh";