If you call the top command, you get all the running processes. But how can I limit the output only to a certain process name like "java"?
I've tried this top -l 2 | grep java but in this way you get only snapshots and not a continuously updated list. And top -l 0 | grep java is not really clear.
Find the pids of the processes you want to monitor and then use the
-p
option which allows you to provide a list of pids to thetop
command.Example:
(I believe you can also pass in a comma-separated list.)
Expanding on @dogbane's answer, you can get all the PIDs for a named process with
pgrep
to do the following:Using the answer from here I was able to create a one liner
This works for me on MacOS 10.12 (Sierra)
I prefer the following so I can still use top interactively without having to look up the pids each time I run it:
Of course if the processes change you'll have to re-run the command.
Explanation:
pgrep process-name
returns a list of process ids which are separated by newlinestr "\\n" ","
translates these newlines into commas, because top wants a comma-separated list of process idssed
is a stream editor, andsed 's/,$//'
is used here to remove the trailing commaI solved my problem using:
in this case: -n is used to set how many times top will what proccess
and -b is used to show all pids
it's prevents errors like : top: pid limit (20) exceeded
The following code updates a list of processes every 5 seconds via the watch command:
watch -n 5 -t top -b -n 1 -p$(pgrep java | head -20 | tr "\\n" "," | sed 's/,$//')