You're echoing the results of the ssh command - which completed successfully both times (ie ssh was ok). You're not displaying the results of the command you ran via ssh.
If you direct the output of the command to a file (via tee or just normal redirection), you can collect the results later.
edit
Due to downvotes (I presume from OP who doesn't realize what I've already answered is correct (see comments)), I'm expanding this answer.
When you run echo $?
, it will output the exit code of the last run local command. For example:
$ ssh user@host 'ls /tmp'
lastSubredditNeighborsRun.log
meetupDumper.log
mongodb-27017.sock
$ echo $?
0
That's the return code of ssh - NOT the return code of the ls
run remotely.
Running echo $?
might also not display anything:
$ ssh user@host 'ls /tp' && echo $?
ls: cannot access /tp: No such file or directory
Or it might display an error return code - if you don't run it chained on the command line:
$ ssh user@host 'ls /tp'
ls: cannot access /tp: No such file or directory
$ echo $?
2
ssh may send back the sent command's error code - it's supposed to - as its own error code ... but it doesn't always.
But running echo $?
is always only going to be able to echo the error code of the most recently-run local command. If ssh returns the remote error code as its own, that's awesome. But if it doesn't (or the remote command doesn't send an error code), you're going to get the expected result from echo $?
- which is 0
if the previous command ran successfully.