在bash中重定向输出

时间:2010-11-11 18:41:20

标签: bash redirect

这就是我想要做的事情:

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

在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

我想将输出捕获到变量或文件中。我该怎么做?

谢谢!

3 个答案:

答案 0 :(得分:2)

Bash使用>进行标准输出重定向。一个例子是:

./test.sh > outfile.txt

如果您有兴趣添加而不是替换outfile.txt,请使用>>代替>。两者都重定向标准输出。

但是,在这种情况下,time命令的输出将是标准错误,因此您必须使用2>而不是>

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

这几乎可以工作,但是time命令与sh shell命令分开工作,因此只有sh命令的输出将被重定向到outfile.txt使用上面的命令命令。要包含time命令的输出,我们需要将整个命令包装在括号中,如下所示:

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

答案 1 :(得分:2)

你可以这样做:

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

由于您需要重定向timedd的输出,因此需要将整个内容包含在(..)中。

timedd都将其输出发送到stderr,因此使用>将无效,您需要2>重定向stderr。

要在变量中获取输出,您可以这样做:

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

答案 2 :(得分:1)

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

>是重定向命令