Reputation: 2574
I want to check exit
command is executed success in a ssh session.
My first attempt is using the command exit && echo $? || echo $?
.The echo $? || echo $?
,it should print 0 if exit successful.
The problem is echo
never execute if exit
execute success because connection is disconnected and the later command is lost.
My second attempt is splitting the command to two command, as this:
$ exit
$ echo $?
echo $?
should be 0
if exit
execute successful.
But another problem is echo $?
maybe be swallowed because it send so quickly that arrived to the remote ssh host before exit
be executed.
So, how to ensure exit
is executed at remote host before send next command?
UPDATE
The using stage is I execute shell command at a program language and send message by a ssh pipe stream.So, I don't know the exit command executed time.If the exit command not completed, my follow commands will be swallowed because they send to the exiting host.
That is why I'm care about the exit command executed.
Upvotes: 0
Views: 887
Reputation: 2574
Inspired by @9Breaker.
I has solved this by calling echo 'END-COMMAND'
flag repeatedly with a spare time, such as 15ms.
To clarify this by a shell channel example:
echo '' && echo 'BEGIN-COMMAND' && exit
echo 'END-COMMAND'
//if not response repeat send `echo 'END-COMMAND'`
echo $? && echo 'END-COMMAND'
//if not response repeat send `echo 'END-COMMAND'`
echo $? && echo 'END-COMMAND'
We can pick up IO stream chars and parse streaming util match BEGIN-COMMAN and END-COMMAND.
the response maybe success:
BEGIN-COMMAND
0
END-COMMAND //should be send multi times to get the response
or fail if network broken when connecting:
BEGIN-COMMAND
ssh: connect to host 192.168.1.149 port 22: Network is unreachable
255
END-COMMAND
Upvotes: 1
Reputation: 724
If your main concern is knowing that you are back to your local machine, then you could define a variable earlier in your script that is just known on your local machine before ssh. Then after exiting you could test for the existence of that variable. If it exists you are back on the local machine and if it does not then try to exit again because you are not back on your local machine.
#define this before ssh
uniqueVarName333=1
Then in your script:
# ssh stuff
exit
if [ -z ${uniqueVarName333+x} ]; then exit; else echo "Back on local machine"; fi
Or you could just check for the success of exit multiple times to ensure that it is successful when you command it to the remote machine.
exit || exit || exit #check it as many times as you feel to get the probability of exiting close to 0
Upvotes: 1