在bash中,调用foo将在stdout上显示该命令的任何输出。

调用foo>output会将该命令的任何输出重定向到指定的文件(在本例中为“output”)。

是否有方法将输出重定向到文件并将其显示在stdout上?


当前回答

要添加的内容。。。

在fedora和redhat unix版本下,软件包的非缓冲区对某些软件包存在支持问题。

抛开烦恼

跟踪对我有用

bash myscript.sh 2>&1 | tee output.log

谢谢ScDF和matthew,您的输入为我节省了大量时间。。

其他回答

<command>|&tee filename#这将创建一个文件“filename”,其中命令状态为内容。如果文件已经存在,它将删除现有内容并写入命令状态。

<command>|tee>>filename#这将向文件附加状态,但不会在standard_output(屏幕)上打印命令状态。

我想通过在屏幕上使用“echo”来打印一些内容,并将这些echo数据附加到文件中

echo "hi there, Have to print this on screen and append to a file" 

所需的命令名为tee:

foo | tee output.file

例如,如果您只关心stdout:

ls -a | tee output.file

如果要包含stderr,请执行以下操作:

program [arguments...] 2>&1 | tee outfile

2> &1将通道2(stderr/标准错误)重定向到通道1(stdout/标准输出),以便将两者都写入stdout。在tee命令中,它还指向给定的输出文件。

此外,如果要附加到日志文件,请使用tee-a作为:

program [arguments...] 2>&1 | tee -a outfile

自从这个用例把我带到这里以来,我得到了额外的答案:

如果您需要作为其他用户执行此操作

echo "some output" | sudo -u some_user tee /some/path/some_file

请注意,echo将在您的时候发生,文件写入将在“some_user”的时候发生。如果您将echo作为“some_uuser”运行,并使用>>“some_file”重定向输出,则不会起作用,因为文件重定向将在您身上发生。

提示:tee还支持附加-a标志,如果您需要将文件中的一行替换为其他用户,则可以作为所需用户执行sed。

tee是完美的,但这也能完成任务

ls -lr / > output | cat output

要添加的内容。。。

在fedora和redhat unix版本下,软件包的非缓冲区对某些软件包存在支持问题。

抛开烦恼

跟踪对我有用

bash myscript.sh 2>&1 | tee output.log

谢谢ScDF和matthew,您的输入为我节省了大量时间。。