• Uncategorized

About bash : setting-a-local-bash-variable-from-an-ssh-command

Question Detail

I am running a chain of sshpass > ssh > commands, I would like to store the exit code of one of those commands ran in the remote server in a variable so I can access it back in the local after ssh is done. What I have done so far does not seem to store anything. Help please!

My Code:

    sshpass -p password ssh [email protected] "echo \"first command\" ; su -lc \"./root_script.sh\" ; set MYVAR = $? ; rm root_script.sh \" 
if (( $MYVAR != 0 )) ; then
     echo "Cannot continue program without root password"
     exit
fi

Problem:
The commands are all executed (the script runs ok) but the variable MYVAR is not set. I have initialized this to a weird number, and the value does not change. The su exit code is not stored!

Notes:

1) I don’t want to do MYVAR=$(ssh….) since ssh is nested within a sshpass, and I don’t want the exit code of either of those, I want the return code of the su command ran in the remote server

2) I have used set command because simple assignment gives me an error saying command is not recognized.

3) I have tried different forms of quoting ( \$? or ‘$?’ or “$?” ) but none seem to work

4) I have tried exporting MYVAR to an environment variable, and I have tried unsetting it prior to the line of code. Still no value is stored.

Question Answer

First, you need to put the content you want to capture on stdout of the process.

Second, you need to use single-quotes, not double-quotes, for the remote command — otherwise, $? will be replaced with its local value before the string is ever passed to ssh!

exit_status=$(sshpass -p password ssh [email protected] 'echo "first command" >&2; \
              su -lc "./root_script.sh" >&2; echo "$?"; rm root_script.sh')
echo "Exit status of remote command is $exit_status"

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.