简体   繁体   English

如何捕获几个命令的输出?

[英]How to capture output of several commands?

I have command producing output belonging to different commands. 我有命令产生属于不同命令的输出。

s=$(time dd if=<source> of=/dev/null bs=<number> count=<number> 2>&1)

$s will contain output only from dd command. $s将仅包含来自dd命令的输出。 How can I have another variable which will contain the output from time ? 我怎样才能有另一个包含time输出的变量?

Try the following: 请尝试以下方法:

s=$({ time dd ... > /dev/null;} 2>&1)

Chepners answer gave me inspiration for the arguably better: Chepners的答案给了我更好的灵感:

s=$(exec 2>&1; time dd ... > /dev/null)

$() is already a subshell, so no need to create an extra subshell. $()已经是子shell,因此无需创建额外的子shell。 Putting exec 2>&1; exec 2>&1; before the command redirects the stdout of the entire subshell, putting it after the command would make it part of the command to time and hence is applied only to the command passed to time . 前命令会将整个子shell的标准输出,把它的命令后,将使该命令的一部分time ,因此只适用于传递给命令time Omitting the exec and semicolon will try to execute the system time binary intead of the builtin, and error out if that does not exist. 省略exec和分号将尝试执行内置的系统time二进制intead,如果不存在则输出错误。 Omitting just the exec but keeping the semicolon will not work as that would cause only newly forked processes to be redirected and the time builtin will not be a new process. 省略exec但保留分号将不起作用,因为只会导致重新定向新的分叉进程,并且内置时间不会是新进程。

Oh and by the way, the > /dev/null does not dump the output of time itself to /dev/null because it too is part of the command that time executes and is not applied to time itself. 哦,顺便说一句, > /dev/null不会将time本身的输出转储到/ dev / null,因为它也是time执行的命令的一部分,不会应用于时间本身。

Hello I just find out the answer. 你好,我找到了答案。

The link from Vlad in comments gave me direction. 弗拉德在评论中的链接给了我指导。

I can use subshells. 我可以使用子壳。

My command could be specified 我的命令可以指定

s=$((time dd if=<source> of=/dev/null bs=<number> count=<number> 2>&1 | tail -n1) 2>&1)

Then I can have $s variable containing all data and I can have array and get values. 然后我可以有$ s变量包含所有数据,我可以有数组和获取值。

The bash built-in time is a special built-in that writes to standard error of the current shell, so you cannot simply redirect its output. bash内置time是一个特殊的内置函数,它写入当前shell的标准错误,因此您不能简单地重定向其输出。 Instead, you would need to run it in a subshell whose standard error has already been redirected. 相反,您需要在其标准错误已被重定向的子shell中运行它。 This causes the "real" command to also run in a subshell, so you can't simply assign its output to variable, as that variable will go away with the subshell. 这导致“真实”命令也在子shell中运行,因此您不能简单地将其输出分配给变量,因为该变量将随子shell一起消失。 Try this: 试试这个:

s=$( exec 2>time.txt; time echo foo )
t=$(< time.txt)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM