Windows CMD "or" Symbol ("||") Only Works Sometimes
Solution 1:
I believe this is happening because
ssh
occasionally exits with an error status for some reason
An interactive shell terminated with Ctrl+c, exit
or logout
exits with the exit status of the last command executed in the shell. In your case the shell is remote and if there is no problem with the local ssh
itself then ssh
will repeat the remote exit status locally. The reason you're talking about is the last command in the shell; it apparently failed and its non-zero exit status propagated to the local side.
Possible solutions:
-
Always
exit 0
orlogout 0
by hand (inconvenient). -
Use
trap … EXIT
in the remote shell and executeexit 0
in the trap (cumbersome). -
Put
exit 0
as the last command in.bash_logout
or equivalent script. This is specific to the shell you're using on the remote side, some shells don't provide this functionality. The code in the script may be conditional (check if the parent process issshd
; or check if theSSH_CONNECTION
variable is in the environment). -
Instead of
ssh -o ConnectTimeout=3 [email protected]
use:ssh -t -o ConnectTimeout=3 [email protected] '"$SHELL"; exit 0'
Disadvantages:
- there are two nested shells on the remote side;
- your remote shell may modify its behavior when invoked from
sshd
; in this case the outer shell will do this, but the inner shell won't, this may cause the whole setup behave not exactly as you wish.
-
Check the actual exit status of
ssh
(locally); it will be255
if an error occurs. You need to replace||
with some logic that tells apart255
from any other exit status. I cannot reliably write this for you because I don't knowcmd.exe
good enough. I guess it will be likeif ERRORLEVEL 255 ssh …
.Note if the remote shell returns
255
then it will make your local code thinkssh
failed. There is no easy way to avoid this. Nevertheless testing against255
is the solution I would choose if I were you. I actually do this in my SSH wrapper that tries several connection parameters.