Bash 将输出分配给此处文档中的变量 [英] Bash assign output to variable inside here document

查看:44
本文介绍了Bash 将输出分配给此处文档中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

bash 脚本中,我需要 ssh 到服务器并执行一些命令,到目前为止我得到的是这样的:

In a bash script, what I need is to ssh to a server and do some commands, what I got so far is like this:

outPut="ss"
ssh user@$serverAddress << EOF
cd /opt/logs
outPut="$(ls -l)"
echo 'output is ' $outPut
EOF
echo "${outPut}"

但是终端的输出是:

output is  ss
ss

output 被赋值给命令 ls -l 的输出,但显示的仍然是原始值,即 ss.这里有什么问题吗?

The output was assigned to the output from command ls -l, but what it showed is still the original value, which is ss. What's wrong here?

推荐答案

这里实际上有两个不同的问题.首先,在 here-document 中,在将文档发送到命令之前,shell 会评估变量引用和命令替换.因此,$(ls -l)$outPut 在发送(通过 ssh)到远程计算机之前在本地计算机上进行评估.您可以通过转义 $s(可能还有一些其他字符,例如您想要发送到远端的转义字符)或将 here-doc 定界符括在引号中来避免这种情况(ssh user@$serverAddress << "EOF") 关闭文档的该功能.

There are actually two different problems here. First, inside a here-document, variable references and command substitutions get evaluated by the shell before the document is sent to the command. Thus, $(ls -l) and $outPut are evaluated on the local computer before being sent (via ssh) to the remote computer. You can avoid this either by escaping the $s (and maybe some other characters, such as escapes you want sent to the far side), or by enclosing the here-doc delimiter in quotes (ssh user@$serverAddress << "EOF") which turns that feature off for the document.

其次,在远程计算机上发生的变量赋值保留在远程计算机上.本地和远程 shell 无法共享状态.如果您想要来自远程计算机的信息,您需要将其作为脚本远程部分的输出发送回,并捕获该输出(使用类似 remoteOutput=$(ssh ...)ssh ... >"$tempFile").如果您要发回多个值,则脚本的远程部分必须以本地部分可以解析它的方式格式化其输出.另外,请注意远程部分的任何其他输出(包括错误消息)都会混入,因此您必须仔细解析以获取您想要的值.

Second, variable assignments that happen on the remote computer stay on the remote computer. There's no way for the local and remote shells to share state. If you want information from the remote computer, you need to send it back as output from the remote part of the script, and capture that output (with something like remoteOutput=$(ssh ...) or ssh ... >"$tempFile"). If you're sending back multiple values, the remote part of the script will have to format its output in such a way that the local part can parse it. Also, be aware that any other output from the remote part (including error messages) will get mixed in, so you'll have to parse carefully to get just the values you wanted.

这篇关于Bash 将输出分配给此处文档中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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