When redirecting top to a file, why does cat command on that file display output of multiple top attempts?

I am customizing a Linux system with a kernel of 6.4.0, and I have noticed a strange issue. When I execute top > a.txt and then open a window to execute cat a.txt, I find that the cat a.txt result is the result of multiple top attempts, but I wouldn’t have this problem with other Linux systems. In other Linux systems, the cat command only displays the results of the top command once. I don’t know why?

# top > a.txt
# cat a.txt
# ls /usr/bin/top -ltr
lrwxrwxrwx    1 1000     1000            17 Aug 23 02:34 /usr/bin/top -> ../../bin/busybox

add top type:

# type top
top is /usr/bin/top
Asked By: ABeginner


Some top implementation (e.g. on OpenBSD, but presumably on some Linux systems too) detects whether its output is going to the terminal or to something that isn’t a terminal (to a pipe or to a file) and changes its behaviour depending on this. If the output goes to a terminal, the utility will be in interactive mode, accepting input from the user and regularly updating its display. When the output goes elsewhere, then top runs in non-interactive mode and will, by default, just output one "screen" of results and then quit.

The top implementation included in Busybox does not do this and will continue to output screen updates even when output goes into a file or pipe. Each update will be preceded by a control character sequence that clears the screen, so cat should show you the final screen update (unless the terminal is not interpreting the control characters), while if you open the file in an editor or use less to view its content, you may see several consecutive screen updates. This also seems to be the case for the procps-ng variant of top sometimes found on Linux systems.

If you want Busybox’s top only to output a single screen of output to a file, use

top -n 1 >file

As to why this is so, it just comes down to the developers of the various top implementations having implemented the tool differently. If you want further information about the decisions taken while implementing the top utility in Busybox, you may want to ask in a Busybox-specific forum or mailing list.

Answered By: Kusalananda
Categories: Answers Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.