Piping an interactive session to a file

2019-01-14 08:57发布

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.

标签: bash unix tee
4条回答
我想做一个坏孩纸
2楼-- · 2019-01-14 09:21

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 -a file.log | program | tee -a file.log
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-01-14 09:27

script — make typescript of terminal session:

script -c "myprogram" file.log

The whole session will be logged to file.log

查看更多
何必那么认真
4楼-- · 2019-01-14 09:28

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

script my-interactive-session.log program
查看更多
欢心
5楼-- · 2019-01-14 09:33

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
查看更多
登录 后发表回答