简体   繁体   中英

how to flush with shell command

are there an equivalent of the C function fflush() for shell command?

echo "kkkk"
flush <<< are there some command to execute to flush stdout?

Short answer: There is no need to perform explicit flush for shell scripts. All shell output (via echo) is NOT buffered. The output is immediately sent to the output device. The situation is more complex if the output is piped into another program, which may buffer it's output.

Long answer: consider

(echo aaa ; sleep 3  ; echo bbb)

Which will display 'aaa', and after 3 seconds delay, 'bbb' - since the pipe construct will result in the the C program using buffered output.

As noted above, if the output is send (via pipe) to a program which will buffer the output, the first line may be delayed, and displayed at the same time as the second line (after the 3 seconds delay). The solution is to force "line buffering" (or no buffering) on other programs in the pipeline.

For example given a simple "C" program to copy stdin to stdout:

int main() { char b[256] ; while (fgets(b, sizeof(b), stdin) ) fputs(b, stdout) };

and running

(echo aaa ; sleep 3 ; echo bbb  ) | a.out | cat

Will result in buffering in a.out, showing 'aaa' and 'bbb' after 3 seconds delay.

No, you should never need it.

When a program, such as echo , exits, all output data is automatically flushed. If the program has not exited yet then flushing is an internal matter and nothing to do with the shell.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM