Command executed via ssh does not return proper return code

Reason:

echo $?, you're actually sending a local variable $? and asking to echo it out in ssh shell, it seems. You can prove that by using not existing command before your ssh statement. For example:

notexistingcommand; ssh vm "echo $?" outputs

bash: nonexistentcommand: command not found

127

or even

export var=123; ssh vm "echo $var" outputs

123

Solution:

What you can do to use the remote variable is escaping and that will spit out -1 (or 127):

ssh vm "nonexistentcmd; echo \$?"

Or you can use single quotes (') as they do not expand variables and take $ symbol literally

ssh vm 'nonexistentcmd; echo $?'


Instead of saying:

ssh vm "bullshitcommand; echo $?"

say:

ssh vm "bullshitcommand"
echo $?

The return code of ssh would be the same as that of the remote command.

Tags:

Bash

Ssh