【问题标题】:Piping an interactive session to a file将交互式会话通过管道传输到文件
【发布时间】:2013-09-15 11:56:36
【问题描述】:

我制作了一个基本上是解释器的玩具交互式控制台程序:

$ myprogram
> this is user input
this is program output

我想将整个会话(包括用户输入和程序输出)通过管道传输到日志文件中。我可以这样做:

$ cat | tee >(myprogram | tee -a file.log) >> file.log
> this is user input
this is program output
$ cat file.log
> this is user input
this is program output

所以上面的会话会像往常一样显示在终端上,但也会复制到日志文件中。

有没有更好的方法来做到这一点?我不喜欢我必须两次写入日志文件,也不喜欢在运行此命令之前必须记得擦除它。

【问题讨论】:

  • Tee 命令用于将输出重定向到文件。基本上,如果您编写 $output | 它会将您的输出复制到文件中。 tee file.log 它将输出复制到 file.log

标签: bash unix tee


【解决方案1】:

script — 制作终端会话的打字稿:

script -c "myprogram" file.log

整个会话将被记录到 file.log

【讨论】:

  • 这可行,但它会捕获所有字符(包括转义序列),这可能会使日志文件难以阅读
【解决方案2】:

由于两个进程无法读取相同的输入,因此需要两个 tee,一个读取终端输入并写入程序标准输入和 file.log,另一个读取程序标准输出并写入终端输出和 file.log:

tee -a file.log | program | tee -a file.log

【讨论】:

  • 谢谢。我给了 konsolebox 的答案,因为他比你领先了大约 3 分钟,但这个解释让我对使用两次 tee 感觉更好。
【解决方案3】:

更简单的形式可以是

tee >(myprogram) | tee -a file.log

如果您想防止输入再次显示在屏幕上:

tee -a file.log | myprogram | tee -a file.log

【讨论】:

  • 谢谢,我没有意识到 tee 会默认从标准输入读取,因此对 cat 的调用是多余的。很遗憾我不得不写两次 file.log 但不是世界末日。
【解决方案4】:

一个简单的方法是使用 script 命令。它只存储您的整个终端会话。运行它:

script my-interactive-session.log program

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-11
    • 1970-01-01
    • 1970-01-01
    • 2019-01-24
    • 2013-05-06
    相关资源
    最近更新 更多