Linux 强制 shell 脚本 fflush

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

Force a shell script to fflush

linuxbashshell

提问by Tim Post

I was wondering if it was possible to tell bash that all calls to echoor printfshould be followed up by a subsequent call to fflush()on stdout/stderr respectively?

我想知道是否有可能告诉 bash对 stdout/stderr 的所有调用echoprintf应该随后分别调用fflush()stdout/stderr?

A quick and dirty solution would be to write my own printf implementation that did this and use it in lieu of either built in, but it occurred to me that I might not need to.

一个快速而肮脏的解决方案是编写我自己的 printf 实现来执行此操作并使用它代替内置的任何一个,但我突然想到我可能不需要这样做。

I'm writing several build scripts that run at once, for debugging needs I reallyneed to see messages that they write in order.

我正在编写几个同时运行的构建脚本,为了调试需求,我真的需要查看它们按顺序编写的消息。

采纳答案by pixelbeat

If comands use stdio and are connected to a terminal they'll be flushed per line. Otherwise you'll need to use something like stdbuf on commands in a pipe line http://www.pixelbeat.org/programming/stdio_buffering/

如果命令使用 stdio 并连接到终端,则每行都会刷新它们。否则,您将需要对管道中的命令使用 stdbuf 之类的东西 http://www.pixelbeat.org/programming/stdio_buffering/

tl;dr: instead of printf ...try to put to the script stdbuf -o0 printf .., or stdbuf -oL printf ...

tl;dr: 而不是printf ...尝试放入脚本stdbuf -o0 printf ..,或者stdbuf -oL printf ...

回答by user3694063

Maybe "stty raw" can help with some other tricks for end-of-lines handling. AFAIK "raw" mode turns off line based buffering, at least when used for serial port ("stty raw < /dev/ttyS0").

也许“stty raw”可以帮助一些其他的行尾处理技巧。AFAIK“原始”模式关闭基于行的缓冲,至少在用于串行端口时(“stty raw < /dev/ttyS0”)。

回答by Dan Hale

If you force the file to be read, it seems to cause the buffer to flush. These work for me.

如果强制读取文件,似乎会导致缓冲区刷新。这些对我有用。

Either read the data into a useless variable:

要么将数据读入一个无用的变量中:

    x=$(<$logfile)

Or do a UUOC:

或者做一个UUOC:

    cat $logfile > /dev/null