setting a local bash variable from an ssh command

社会主义新天地 提交于 2021-02-05 09:46:54

问题


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 user@ip "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.


回答1:


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 user@ip 'echo "first command" >&2; \
              su -lc "./root_script.sh" >&2; echo "$?"; rm root_script.sh')
echo "Exit status of remote command is $exit_status"


来源:https://stackoverflow.com/questions/25003521/setting-a-local-bash-variable-from-an-ssh-command

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!