bash Linux终端输出重定向

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/588144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 20:42:42  来源:igfitidea点击:

Linux terminal output redirection

linuxbashredirect

提问by Jon Ericson

I want to redirect the output of a bash script to a file.

我想将 bash 脚本的输出重定向到一个文件。

The script is:

脚本是:

#!/bin/bash
echo "recursive c"
for ((i=0;i<=20;i+=1)); do
time ./recursive
done

But if I run it like this:

但是如果我像这样运行它:

script.sh >> temp.txt

only the output of ./recursive will be captured in the file.

只有 ./recursive 的输出会被捕获到文件中。

I want to capture the output of time command in the file.

我想在文件中捕获 time 命令的输出。

回答by Jon Ericson

Redirect STDERRto STDOUT:

重定向STDERRSTDOUT

script.sh >> temp.txt  2>&1

Or if using bash4.0:

或者如果使用bash4.0:

$ script.sh &>> temp.txt

(Thanks for the second form go to commenter ephemient. I can't verify as I have an earlier bash.)

(感谢第二个表格转到评论者 ephemient。我无法验证,因为我有一个更早的bash.)



My tests were surprising:

我的测试令人惊讶:

$ time sleep 1 > /dev/null 2>&1

real    0m1.036s
user    0m0.002s
sys     0m0.032s

The problem is the redirection was included as part of the command to be timed. Here was the solution for this test:

问题是重定向作为要计时的命令的一部分包含在内。这是此测试的解决方案:

$ (time sleep 1) > /dev/null 2>&1

I don't think this is part of your problem, but it seemed worth a mention.

我不认为这是您问题的一部分,但似乎值得一提。

回答by CenterOrbit

I prefer the &>> method better, but this is a solution as well:

我更喜欢 &>> 方法,但这也是一个解决方案:

$ script.sh 2>&1 |tee -a temp.txt