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 or logout 0 by hand (inconvenient).

  • Use trap … EXIT in the remote shell and execute exit 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 is sshd; or check if the SSH_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 be 255 if an error occurs. You need to replace || with some logic that tells apart 255 from any other exit status. I cannot reliably write this for you because I don't know cmd.exe good enough. I guess it will be like if ERRORLEVEL 255 ssh ….

    Note if the remote shell returns 255 then it will make your local code think ssh failed. There is no easy way to avoid this. Nevertheless testing against 255 is the solution I would choose if I were you. I actually do this in my SSH wrapper that tries several connection parameters.