【发布时间】:2015-09-30 14:37:07
【问题描述】:
我正在尝试将通过 SSH 运行的脚本(位于远程服务器上)的输出捕获到一个变量中,下面是我的代码:
ssh username@hostname << EOF
variable=`./script_on_remote_server.sh`
echo $variable
EOF
当我运行上述脚本时,变量中没有存储任何内容,并且该变量的回显没有返回任何内容。
我做错了什么?
【问题讨论】:
我正在尝试将通过 SSH 运行的脚本(位于远程服务器上)的输出捕获到一个变量中,下面是我的代码:
ssh username@hostname << EOF
variable=`./script_on_remote_server.sh`
echo $variable
EOF
当我运行上述脚本时,变量中没有存储任何内容,并且该变量的回显没有返回任何内容。
我做错了什么?
【问题讨论】:
对于要在远程计算机中评估的./script_on_remote_server.sh。您需要用<< 'EOF' 引用<< EOF 并将-T 添加到您的ssh 命令中。
ssh -T username@hostname << 'EOF'
variable=`./script_on_remote_server.sh`
echo $variable
EOF
【讨论】:
我将首先展示实现此目的的一种方法:
variable=`echo ./script_on_remote_server.sh | ssh username@hostname`
或者如果你使用 bash,我更喜欢这种语法:
variable=$(echo ./script_on_remote_server.sh | ssh username@hostname)
从您的帖子中很难看出,但您似乎正在尝试执行以下操作:
ssh username@hostname <<EOF
variable=./script_on_remote_server.sh
echo $variable
EOF
但是,这里有一些误解。 variable=command 不是将命令输出分配给变量的正确语法;事实上,它甚至不运行命令,它只是将文字值command 分配给variable。你想要的是variable=`command` 或(在 bash 语法中)variable=$(command)。另外,我认为您的目标是让variable 可用于本地机器上的shell。在远程机器上运行的代码中声明variable 不是这样做的方法。 ;) 即使你这样做了:
ssh username@hostname <<EOF
variable=`./script`
echo $variable
EOF
这只是像往常一样在远程主机上运行命令的一种效率较低的方式,因为variable 会立即丢失:
echo ./script | ssh username@hostname
另外,请注意ssh 命令接受作为附加参数运行的命令,因此您可以将整个内容缩写为:
variable=`ssh username@hostname ./script_on_remote_server`
【讨论】: