在bash脚本中将SSH输出捕获为变量 [英] Capturing SSH output as variable in bash script

查看:281
本文介绍了在bash脚本中将SSH输出捕获为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编写bash脚本时,我一直在努力解决此问题. 基本上,我想测量远程服务器上程序的时间,因此我使用以下命令: /usr/bin/time -f %e sh -c "my command > /dev/null 2>&1"执行程序. 但是,看来我根本无法将命令(SSH)的输出捕获到变量中.实际上,结果(时间)一直打印到标准输出.

I've been struggling with this problem when writing a bash script. Basically, I want to measure the time of a program on a remote server, so I use the command: /usr/bin/time -f %e sh -c "my command > /dev/null 2>&1" to execute the program. However, it appears that I cannot capture the output of my command (SSH) to a variable at all. In fact, the result (time) keeps getting printed out to stdout.

完整代码是:

respond=$(ssh ${fromNode} /usr/bin/time "-f" "%e" "'sh' '-c' 'virsh migrate --live ${VM} qemu+ssh://${toNode}/system --verbose > /dev/null 2>&1'")

response的值只是空的,尽管时间已打印到标准输出中.

The value of respond is just empty, though the time is printed out to the standard output.

推荐答案

"time"命令将结果打印到stderr,而不是stdout.因此,它不会通过管道传递到您的变量中.

"time" command prints result to stderr, not to stdout. Thus it is not piped into your variable.

您应该将stderr重新路由到stdout以实现所需的功能:

You should reroute stderr to stdout to achieve what you want:

 result=$(ssh host time "command" 2>&1)

您的完整代码如下所示:

And your full code can look something like this:

 respond=$(ssh ${fromNode} /usr/bin/time "-f" "%e" "'sh' '-c' 'virsh migrate --live ${VM} qemu+ssh://${toNode}/system > /dev/null 2>&1'" 2>&1)

这篇关于在bash脚本中将SSH输出捕获为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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