bash 将交互式会话通过管道传输到文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18812098/
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-18 06:34:02  来源:igfitidea点击:

Piping an interactive session to a file

bashunixtee

提问by Dave

I have made a toy interactive console program that is basically an interpreter:

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

$ myprogram
> this is user input
this is program output

I want to pipe the full session, both user input and program output, into a log file. I can do this like so:

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

$ 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

So the above session will display to the terminal as usual but will also be duplicated to the log file.

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

Is there a better way to do this? I don't like how I have to write the log file twice, nor how I have to remember to wipe it before running this command.

有一个更好的方法吗?我不喜欢我必须两次写入日志文件的方式,也不喜欢我必须在运行此命令之前记住擦除它的方式。

采纳答案by konsolebox

The simpler form could be

更简单的形式可以是

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

If you want to prevent input being shown again to the screen:

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

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

回答by Robert Strind

script — make typescript of terminal session:

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

script -c "myprogram" file.log

The whole session will be logged to file.log

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

回答by Nahuel Fouilleul

As two processes can't read the same input two tees are needed, one which reads terminal input and writes to program standard input and file.log another which reads program standard output and writes into terminal output and file.log:

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

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

回答by sunsations

An easy way is to use the scriptcommand. It just stores your whole terminal session. Run it with:

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

script my-interactive-session.log program