Top command is a useful utility to find out the top CPU consuming processes running on your system. It also displays useful stats such as uptime, average load, used memory and more. It mainly lists all processes and threads running on your system. But it is a live command that runs in real-time with frequent updates. What if you want to save top command’s output to a file? In this article, we will learn how to capture top command output to file.
How to Capture Top Command Output to File
Using -b and -n options you can save top command output to file. -b tells top command to run in batch mode. -n specifies the number of iterations of top command whose output you want to capture to file. Since top command updates frequently, it is important to specify how many of its iterations you want to be saved. Here is the command to save output of one iteration to file top.txt
$ top -b -n 1 > top.txt
You can save top command output to any file as long as you have write access to it. Once you have captured top command’s output, you can view it using cat, less or any similar command.
$ cat top.txt
If you want to capture the output of 3 iterations of top command, use the following command.
$ top -b -n 3 > top3.txt
Please note, when you save multiple iterations of top command to file, you will need to wait for the top command to complete those iterations.
Once you have captured all the required iterations, you can use grep command to filter the required output. Here is a command to get records of mysql process from top command’s output.
$ cat top3.txt |grep mysql 21160 mysql 20 0 1187368 316264 11772 S 0.0 15.6 42:19.12 mysqld 21160 mysql 20 0 1187368 316264 11772 S 0.3 15.6 42:19.13 mysqld 21160 mysql 20 0 1187368 316264 11772 S 1.0 15.6 42:19.16 mysqld
As you can see, there will be 3 records in the output, one from each iteration.
If you only want to save the output of specific process, and not the entire output of top command, use -p option, followed by the PID of the required process. We will use pidof command to find out the PID of MySQL process.
$ pidof mysqld 21160 $ top -p 21160 -b -n3 > mysql.txt
Now you can directly open mysql.txt file to see only MySQL processes’ information.
$ cat mysql.txt 21160 mysql 20 0 1187368 316264 11772 S 0.0 15.6 42:19.12 mysqld 21160 mysql 20 0 1187368 316264 11772 S 0.3 15.6 42:19.13 mysqld 21160 mysql 20 0 1187368 316264 11772 S 1.0 15.6 42:19.16 mysqld
In this article, we have learnt how to capture top command’s output to file, with a couple of common examples. You can use these commands on almost every Linux distribution.
Also read:
How to Check Supported TLS/SSL version in Linux
How to Run Multiple Commands in Linux
How to Record & Replay Terminal Session in Linux
How to Save All Terminal Output to File
How to Remove Startup Applications in Ubuntu
Related posts:
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.