简体   繁体   English

重定向bas​​h中的输出

[英]Redirecting output in bash

Here's what I am trying to do: 这是我想做的事情:

time sh -c "dd if=/dev/zero of=ddfile bs=512 count=125 && sync"

When run that on shell the o/p is 在shell上运行时,o / p为

125+0 records in
125+0 records out
64000 bytes (62.5KB) copied, 0.028935 seconds, 2.1MB/s
real 0m 0.08s
user 0m 0.00s
sys 0m 0.01s

I want to capture the output to a variable or to a file. 我想将输出捕获到变量或文件中。 How do I do that ? 我怎么做 ?

Thanks! 谢谢!

Bash uses > for standard output redirection. Bash使用>进行标准输出重定向。 An example would be: 一个例子是:

./test.sh > outfile.txt

If you're interested in appending to rather than replacing outfile.txt, use >> instead of > . 如果您有兴趣添加而不是替换outfile.txt,请使用>>而不是> Both redirect standard output. 两者都重定向标准输出。

However, the output of the time command in this case will be to standard error, so you must use use 2> rather than > . 但是,在这种情况下, time命令的输出将为标准错误,因此您必须使用use 2>而不是>

time sh -c "dd if=/dev/zero of=ddfile bs=512 count=125 && sync" 2> outfile.txt

This almost works, but the time command works separately from the sh shell command, and thus only the output of the sh command will be redirected to outfile.txt using the above command. 这几乎可以工作,但是time命令与sh shell命令是分开工作的,因此使用上述命令仅将sh命令的输出重定向到outfile.txt。 To include the output of the time command, we need to wrap the entire command in parenthesis, as below: 为了包括time命令的输出,我们需要将整个命令用括号括起来,如下所示:

(time sh -c "dd if=/dev/zero of=ddfile bs=512 count=125 && sync") 2> outfile.txt

You can do: 你可以做:

(time sh -c "dd if=/dev/zero of=ddfile bs=512 count=125 && sync") 2> file

Since you need to redirect the output of both time and dd you need to enclose the entire thing in (..) . 由于您需要重定向timedd的输出,因此需要将整个内容括在(..)

Both time and dd send their output to stderr, so using > will not work, you need 2> which redirects stderr. timedd将其输出发送到stderr,因此使用>将不起作用,您需要2>来重定向stderr。

To get the output in a variable you can do: 要获得变量中的输出,可以执行以下操作:

var=$((time sh -c "dd if=/dev/zero of=ddfile bs=512 count=125 && sync") 2>&1)

time sh -c "dd if=/dev/zero of=ddfile bs=512 count=125 && sync" > ./yourfile 时间sh -c“ dd if = / dev / zero of = ddfile bs = 512 count = 125 && sync”> ./yourfile

> is the redirect command >是重定向命令

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

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