1

I'm very nubby at Java, so please excuse me if is a dummy question. I have the following piece of code, and the execution flow is different from my intention:

channel = session.openChannel("shell");
OutputStream ops = channel.getOutputStream();
PrintStream ps = new PrintStream(ops, true);

channel.connect();
String sudo = "sudo su - user";
String copy = "copy from a to b;

String cd = "cd a directory";
String runload = "run a scrip in unix;
String cd1 = "cd a directoryu";
String executeload = "run a scrip in unix";

ps.println(sudo);
ps.println(copy);
ps.println(cd);
ps.println(runload);
ps.println(cd1 );

if (db.runload().contains("SUCCESS")) {
    ps.println(executeload);

    //execute this only if runload was success

} else {
    System.exit(1);
}

The point is that "if block" is executed before previous lines. runload is script which load information in a table and is a precondition for executeload. In this case executeload will throw java.lang.NullPointerException.

My question is: it Is a way to control the flow in this piece of code? Every previous line is a precondition to the next one. My intention is to execute the next line when the current is finally executed.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
user3660050
  • 103
  • 2
  • 14
  • Most of the time, you don't need to worry about that. The compiler may optimize execution time by alterin the order of execution of statements. – Maurice Perry Jul 31 '17 at 13:58
  • In my case, matters. The execution flow I thought is sequentially, in this way every line of code is a precondition for next one. – user3660050 Aug 01 '17 at 06:59

1 Answers1

0

The println just sends ("types") the command to the server. It does not wait for the command to be completed.

There's actually no way to wait for a command to be completed. A "shell" is a just a black-box with an input and an output. There's even no way to tell, what parts of the output corresponds to which input.

In general, you should use an "exec" channel for automation. The "shell" channel is intended for implementing an interactive terminal.

The "exec" channel closes with its command, so you can clearly tell that a command has finished. You can then open a new "exec" channel for further commands.

See JSch example for "exec" channel.


See also JSch Shell channel execute commands one by one testing result before proceeding.


Things get complicated though with your use of sudo.

See Running command after sudo login.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992