There is a simpler approach that uses ps
formating options and AWK
We know that by default, human users have UID that ranges from 1000 to 65533 ( UID 65534 is nobody
user ).
We also know that ps
has formatting flag -o
, where we can choose to output UID as well as the process. The format would be the following ( note that I am showing here only 5 first lines )
ps -eo uid,cmd | head -n 5
UID CMD
0 /sbin/init
0 [kthreadd]
0 [ksoftirqd/0]
0 [kworker/0:0H]
Thus, we can do
ps -eo uid,cmd | awk '$1 >= 1000 && $1 < 65534 '
AWK helps us to print all lines where column 1, the UID is greater or equal to 1000 AND less than 635534.
Sample output from my system (where I have only one user ):
$ ps -eo uid,cmd | awk '$1 >= 1000 && $1 < 635534 ' | tail -n 5
1000 /usr/lib/at-spi2-core/at-spi2-registryd --use-gnome-session
1000 /usr/lib/firefox/firefox google.com
1000 ps -eo uid,cmd
1000 awk $1 >= 1000 && $1 < 635534
1000 tail -n 5
EDIT
I've realized that OP wanted the number of processes used by human users.
If all you really care about is the number of processes that belong to human users, here's a quick solution:
ps --no-headers -eo uid,args --sort=uid | awk '$1 >= 1000 && $1 < 65534 {counter++}; END{print counter" human processes"}'
As for my previous solution, I've improved the AWK
command, which uses associative arrays, based on UID, as well as added additional flags to ps
command to include username and sort the output by UID.
ps -eo uid,euser,cmd --sort=uid | awk '$1 >= 1000 && $1 < 65534 { HUMAN++; procTotals[$1]++; if( $1 > UID ) username[$1]=$2; UID=$1 } END{ print "Out of "NR" processes, "HUMAN" belong to human users"; for(i=1000;i<=UID;i++ ) print username[i]":"procTotals[i] }'
Sample output:
xieerqi:$ ps -eo uid,euser,cmd --sort=uid | awk '$1 >= 1000 && $1 < 65534 { HUMAN++; >
Out of 215 processes, 88 belong to human users
xieerqi:84
testuser:4
For better readability , here's the formated code. Note that awk portion could be turned into a script with #!/usr/bin/awk -f
shebang line
ps -eo uid,euser,cmd --sort=uid | awk '$1 >= 1000 && $1 < 65534 {
HUMAN++; procTotals[$1]++;
if( $1 > UID ) username[$1]=$2; UID=$1
}
END{ print "Out of "NR" processes, "HUMAN" belong to human users";
for(i=1000;i<=UID;i++ )
print username[i]":"procTotals[i]
}'
ps -u
.