5

I'm writing a script in ksh. I need to find all users who have more than N processes and echo them in the shell. N is read from ksh.

I know that I should use ps -elf, but how do I parse it, find users with >N processes, and create an array with them? I'm having a little trouble with arrays in ksh. Maybe a simple solution can help me instead of having to to create an array. One person recommended that I use

ps -elf | awk '{a[$3]++;}END{for(i in a)if (a[i]>N)print i, a[i];}' N=3

but it doesn't work correctly.

1 Answer 1

11

You should reduce the columns output by ps to the minimum, i.e. request only the username here - this simplifies further processing.

For example:

$ ps -eo user=

will print the owner of all the currently running processes (= suppresses the header).

An easy way to get the counts for each user:

$ ps -eo user= | sort | uniq -c
  1 dovecot
  1 messagebus
  1 mpd
  1 polkitd
  2 postfix
121 root
 27 me

You can then filter that as you wish:

$ ps -eo user= | sort | uniq -c | awk '$1 > 42 {print $2}'
root

With a limit in a variable:

$ N=42
$ ps -eo user= | sort | uniq -c | awk -v limit="$N" '$1 > limit {print $2}'
root
3
  • BEST WAY ! THX!!
    – Alex Zern
    Commented Mar 19, 2013 at 15:02
  • +1 You can also sort the output by the numeric column descending by piping to sort -nrk 1
    – l0b0
    Commented Mar 19, 2013 at 16:08
  • @l0b0, sort -rn will do the same as sort -rnk1, since -n ignores the leading blanks anyway. Commented Mar 19, 2013 at 16:16

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .