Here i used the top command inside a function,and i called the function.
when executing this bash file i get all the process which are using by the kernel
i just want to display only the first 5 running process.
is it possible?
This is not that easy, as it heavily depends on top 's configuration, and on the tools that are available on your system (which, by the way, you fail to mention in your request). My best result on my linux system :
You need one single iteration of top . With -n1 , top leaves cleanly after that. Without it, it is killed because its output pipe has disappeared. Or, grep keeps waiting for more input...
Using top for this kind of task is generally a problem because top with its curses-designed interface was built for interactive use. You might want to consider using a different program.
For instance there is ps , which would also allow to sort for a more specific criteria than "whatever top places first". The process(es) with the most processor-time used? The processes with the most virtual memory allocated? The process using the most real memory? All this (and more) could be a realistic criteria for sorting (and identifying the top 5 of) the processes. With ps you do it this way:
First, look at the various arguments of the (SysV-style-) ps -option "-o" (see the man page): for this example i will use the size of the allocated virtual memory, which is "vsz". I make the virtual memory size the first column, then sort numerically on it. The output is from my system (Linux Fedora Core 22, Kernel 4.4.18):
I suppose one should also ask which way you want to sort your processes. Is it by CPU use at that instant, total CPU use since process start, real memory, virtual memory, IO read, IO writes, file opens, network traffic, is the server using swap heavily etc.
There are many things to consider when a server, application or process is running slowly which may not be a simple "who is using the most CPU?"
Some examples are:
if your code is frequently spawning new processes to perform a menial task (e.g. using echo $var | cut -f1 -d " " in a loop)
if your code repeatedly opens a file to read one item in a loop rather than opening the file as input to the loop
if your code appends single lines to a file in a loop rather than having one output file descriptor for the loop
and many other pitfalls I'm sure.
Is there a particular problem you are having that you need to find out why it's running slow? Some more general information about your server, application and your perceived problem may help us to work on a better answer.