在变量中收集远程ssh命令的输出 [英] Collecting the output of a remote ssh command in a variable

查看:71
本文介绍了在变量中收集远程ssh命令的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在bash脚本中捕获远程命令的输出.例如

How to capture the output of a remote command in a bash script. For example

ssh $USERNAME@$SUT<<EOD
COUNT=$(ls -la | wc -l)
EOD

针对具有多个此类实例的较大脚本进行规划,我需要在其中存储和使用远程命令输出.

Planning this for a larger script with multiple such instances, where I need to store and use the remote command output.

推荐答案

应为:

VAR=$(ssh "$USERNAME"@"$HOST" -- remote_command -option)

您要远程执行 remote_command 并将其存储在本地变量中.这就是上面的命令.

You want to execute remote_command remotely and store it in a variable locally. That's what the above command does.

如果要远程执行多行命令,请使用以下结构以及此处的文档:

If you want to execute a multiline command remotely you use the following construct with a here doc:

VAR=$(ssh "$USERNAME"@"$HOST" <<EOF
    remote_command -option
    another_command
    ...
EOF
)

顺便说一句,除非您希望将局部变量插入到远程命令中,否则您可能想使用<<''EOF'作为开始定界符在here doc中停用局部shell扩展(请注意'):

Btw, unless you want interpolate local variables into the remote command, you probably want to deactivate local shell expansions in the here doc using <<'EOF' as the start delimiter (note the '):

VAR=$(ssh "$USERNAME"@"$HOST" <<'EOF'
    remote_command -option
    another_command
    ...
EOF
)

在上述形式中,您可以在远程脚本中使用shell变量,命令替换等.像这样:

In the above form you can use shell variables, command substitution etc in the remote script. Like this:

VAR=$(ssh "$USERNAME"@"$HOST" <<'EOF'
    COUNT=$(remote_command -option)
    another_command "${COUNT}"
    if $((COUNT+1)) ; then
        foo -bar
    fi
    ... and so on. all expansions happen remotely
EOF
)

这篇关于在变量中收集远程ssh命令的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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