How to Save htop Output to Text File in Ubuntu
This guide explains how to export process monitoring data similar to htop into a text file on Ubuntu. Since htop is an interactive terminal user interface, standard redirection commands do not produce readable text. You will learn the most effective command-line alternatives and recording methods to capture this system information accurately.
Why Direct Redirection Fails
You cannot simply run htop > file.txt because htop
uses ncurses to draw dynamic interfaces. This method saves ANSI escape
codes instead of plain text, resulting in an unreadable file. To get
usable data, you must use commands designed for static output or record
the terminal session.
Method 1: Using the ps Command
The most reliable way to save process data to a text file is using
the ps command with sorting options. This provides a static
snapshot similar to the htop view without interface codes. Run the
following command in the terminal:
ps aux --sort=-%cpu | head -n 11 > htop_data.txtThis command lists all processes, sorts them by CPU usage, takes the
top 11 lines including the header, and saves them to
htop_data.txt. You can change -%cpu to
-%mem to sort by memory usage instead.
Method 2: Using the script Command
If you need to record the visual session exactly as it appears in the
terminal, use the script utility. This records everything
displayed on the screen, including control characters, but preserves the
session flow. Start the recording with:
script -c "htop" htop_session.txtPress Ctrl + D or type exit to stop the
recording. Note that the resulting file may contain terminal control
codes and is best viewed with cat or a text editor that
handles escape sequences.
Method 3: Manual Copy and Paste
For a quick one-time capture without commands, you can manually copy
the visible text from the terminal buffer. Open htop, select the text
you wish to save with your mouse, and press
Ctrl + Shift + C. Open a text editor, paste the content
with Ctrl + V, and save the file. This method captures only
what is currently visible on the screen.