Top utility in bash for loop

Dear All,

is it possible to use top utility in for loop?

I am trying to get top swap space consuming processes in my for loop.
I got multiple way (using /proc FS) however have anybody used top command in for loop? Using /proc FS giving solutionbut itrs more complex. Please suggest if anybody has simpler solution

You can do the following to achieve this:-

  • Run top command

top

  • Press O and then p to select sort by SWAP usage.
  • Press W to save this settings it to .toprc file
  • Now you can put below command in loop to get the list of processes sorted by SWAP usage:-

top -n 1

I hope this helps.

1 Like

Thanks for reply Bipin!!!

However this method works only on terminal... any trick to use it in bash script/loop...

I meant, how the script will understand option O and P in for loop/shell script

Once you have saved the settings to .toprc using W option, then you don't have to use option O & p anymore. Your top command will always display processes sorted by SWAP usage. Please give it a try and see if you are getting the desired result.

Hi, you can use something like:

top -o size -n 1