5

I am writing a bash script and I am using

ps -e -o %cpu

command.

I would like to have output of sorted %cpu values (descending). How to do that? I know that I should use sort command but I don't know how.

Nakilon
  • 34,866
  • 14
  • 107
  • 142
user1926550
  • 539
  • 5
  • 10
  • 18
  • 1
    Are you looking for something simple as `ps -e -o %cpu | sort -r` ? – tessi Apr 21 '13 at 08:48
  • Please avoid *"Give me the codez"* questions that have been asked and answered so many times you have to make an effort to avoid finding an answer. Also see [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/q/261592/608639) – jww Jun 25 '18 at 10:27

2 Answers2

14
 ps -e -o %cpu | sort -nr

n for numeric, r for reverse. If you also want to remove the header:

 ps -e -o %cpu | sed '1d' | sort -nr
perreal
  • 94,503
  • 21
  • 155
  • 181
  • One more question. I want to use read command but without having to click return button (enter) at the end. Lets say... a script is running and if user presses 'q' button on the keyboard, the script ends – user1926550 Apr 21 '13 at 09:12
1

ps has an inbuilt option that sorts its output, based on any field of choice. You can use

ps k -%cpu -e -o %cpu

Here, k sorts the output based on field provided and -%cpu is to sort it in descending order.

If you omit the - in front of the sort field then it will be sorted in ascending order. Also note that you can give it multiple sort fields:

ps k -%cpu,-%mem -e -o %cpu,%mem

This sorts the output(in descending order for both) first based on the %cpu field and second based on %mem field.

n3rV3
  • 1,096
  • 8
  • 10