10

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.

2
  • 1
    Are you looking for something simple as ps -e -o %cpu | sort -r ? Commented Apr 21, 2013 at 8: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? Commented Jun 25, 2018 at 10:27

2 Answers 2

19
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
Sign up to request clarification or add additional context in comments.

1 Comment

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
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.