1

I'm trying to get the last return code from an SSH shell in linux. I'm using the command:echo &? to get it. I've written following code but it's not working:

int last_len = 0;
Pattern p = Pattern.compile("echo $?\r\n[0-9]");
while(in.available() > 0 ) {
    last_len = in.read(buffer);
    String str = new String(buffer, 0, last_len);
    Matcher m = p.matcher(str);
    if(m.find()) {
        return Integer.parseInt(m.group().substring(9));
    }
}

What am I doing wrong?

1 Answer 1

1

You need to escape $, ? in the regex inorder to match the literal form of those characters since ?, $ are considered as special chars in regex.

Pattern p = Pattern.compile("echo \\$\\?\\r?\\n([0-9])");
Matcher m = p.matcher(str);
if(m.find()) {
System.out.println(m.group(1));
}

or

Pattern p = Pattern.compile("echo\\s+\\$\\?[\\r\\n]+([0-9])");
Sign up to request clarification or add additional context in comments.

3 Comments

ya, ...\r called carriage return and \n newline char
so why you replaced it whit \\r?\\n ?
both would work. and also you don't need substring method for extracting the number.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.