guruprasadbhat
guruprasadbhat

Reputation: 17

Exit code of previous command execution is always 0 -- In Remote Shell Execution $?

I am trying to execute a script, In the midway of the script, it executes a part of the code in a remote shell and then again comes back to the same local shell.

However, my question is about the exit codes of the command executed in the remote shell. I am trying to do decision in remote with if-then-else based on the exit codes. When it didn't execute as expected I tried to narrow down the problem.

Here are my findings,

The output is always IP Found, as $? is always equal to 0.

ssh root@<remote server> bash -c "'
host www.google.com123
if [ $? != 0 ]
then
    echo "Invalid Host"
else
    echo "IP Found"
fi

'"

Also, in this case, the same output is expected

ssh root@<remote server> bash -c "'
host www.google.com
if [ $? != 0 ]
then
    echo "Invalid Host"
else
    echo "IP Found"
fi

'"

Ref: I got to know about this remote execution method from here

Please Help me understand this behavior of remote shell execution. Also, if there are any other ways to execute a part of a shell-script in remote through ssh please suggest.

Upvotes: 1

Views: 272

Answers (1)

chepner
chepner

Reputation: 530922

The outermost quotes are double quotes, so $? is expanded locally before you ever run bash remotely. Instead, use

ssh root@<remote server> 'bash -c "
host www.google.com123
if [ \$? != 0 ]
then
    echo \"Invalid Host\"
else
    echo \"IP Found\"
fi

"'

Simpler is to avoid checking $? explicitly at all:

ssh root@<remote server> 'bash -c "
if ! host www.google.com123
then
    echo \"Invalid Host\"
else
    echo \"IP Found\"
fi

"'

Even simpler is not run a second unnecessary shell.

ssh root@<remote server> '
if ! host www.google.com123
then
    echo "Invalid Host"
else
    echo "IP Found"
fi
'

Upvotes: 3

Related Questions