从ssh命令设置本地bash变量 [英] setting a local bash variable from an ssh command

查看:64
本文介绍了从ssh命令设置本地bash变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行sshpass> ssh>命令链,我想将在远程服务器中运行的那些命令之一的退出代码存储在变量中,以便在ssh完成后可以在本地重新访问它.到目前为止,我所做的似乎没有存储任何内容.请帮忙!

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!

我的代码:

    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

问题:所有命令均已执行(脚本运行正常),但未设置变量MYVAR.我已经将其初始化为一个怪异的数字,并且该值不变.su退出代码未存储!

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!

注意:

1)我不想做MYVAR = $(ssh ....),因为ssh嵌套在sshpass中,并且我不希望其中任何一个的退出代码,我想要的返回代码是su命令在远程服务器中运行

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)我使用了set命令,因为简单的赋值给我一个错误,指出无法识别命令.

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

3)我尝试了不同形式的引号(\ $?或'$?'或"$?"),但似乎都不起作用

3) I have tried different forms of quoting ( \$? or '$?' or "$?" ) but none seem to work

4)我尝试将MYVAR导出到环境变量,并尝试在代码行之前取消设置它.仍然没有值被存储.

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.

推荐答案

首先,您需要将要捕获的内容放在流程的 stdout 上.

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

第二,对于远程命令,您需要使用单引号而不是双引号-否则,在将字符串传递给ssh之前, $?将被替换为其本地值.!

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"

这篇关于从ssh命令设置本地bash变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆