首页 文章

如何将输出重定向到文件和标准输出

提问于
浏览
713

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

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

有没有办法将输出重定向到文件并将其显示在stdout上?

9 回答

  • 16

    使用 tail -f output 应该工作 .

  • 9

    要添加的东西......

    软件包unbuffer支持fedora和redhat unix版本下的一些软件包的问题 .

    抛开麻烦

    Following worked for me

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

    谢谢ScDF&matthew你的投入为我节省了很多时间..

  • 969

    您想要的命令名为 tee

    foo | tee output.file
    

    例如,如果你只关心stdout:

    ls -a | tee output.file
    

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

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

    2>&1 将通道2(stderr /标准错误)重定向到通道1(标准输出/标准输出),这样两者都写为标准输出 . 它也指向 tee 命令的给定输出文件 .

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

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

    T恤是完美的,但这也将起到作用

    ls -lr / > output | cat output
    
  • 96
    $ program [arguments...] 2>&1 | tee outfile
    

    2>&1 转储stderr和stdout流 . tee outfile 获取它获取的流并将其写入屏幕和文件"outfile" .

    这可能是大多数人都在寻找的 . 可能的情况是某些程序或脚本长时间努力并产生大量输出 . 用户希望定期检查进度,但也希望将输出写入文件 .

    问题(特别是在混合stdout和stderr流时)是依赖于程序刷新的流 . 例如,如果没有刷新对stdout的所有写入,但是刷新了对stderr的所有写入,那么它们将在输出文件和屏幕上按时间顺序排列 .

    如果程序每隔几分钟只输出1或2行来报告进度,那也很糟糕 . 在这种情况下,如果程序没有刷新输出,用户甚至不会在屏幕上看到任何数小时的输出,因为它们都不会被推过管道几个小时 .

    更新:程序 unbufferexpect 包的一部分,将解决缓冲问题 . 这将导致stdout和stderr立即写入屏幕和文件并在组合时保持同步并重定向到 tee . 例如 . :

    $ unbuffer program [arguments...] 2>&1 | tee outfile
    
  • 3

    这个用例带来的奖励回答让我来到这里:

    In the case where you need to do this as some other user

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

    请注意,回显将发生在你身上,并且文件写入将发生"some_user"如果你将echo作为"some_user"运行并且使用>> "some_file"重定向输出, NOT 工作的是什么,因为文件重定向将像你一样发生 .

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

  • 0

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

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

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

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

    另一种对我有用的方法是,

    <command> |& tee  <outputFile>
    

    gnu bash manual所示

    例:

    ls |& tee files.txt
    

    如果使用'|&',则command1的标准错误除了标准输出外,还通过管道连接到command2的标准输入;它是2>&1 |的简写 . 标准错误到标准输出的隐式重定向是在命令指定的任何重定向之后执行的 .

    有关更多信息,请参阅redirection

  • -10

    您可以主要使用Zoredache solution,但如果您不想覆盖输出文件,则应使用-a选项编写tee,如下所示:

    ls -lR / | tee -a output.file
    

相关问题