#!/usr/bin/env bash

# countprocs.bash - counts each users' processes
# Licensed under the terms of the GNU GPLv3 or later
# Proprietary Software Must Perish!

# AUTHOR: Johannes Truschnigg ( johannes@truschnigg.info || https://johannes.truschnigg.info )

#!/usr/bin/env bash

[ "${BASH_VERSINFO[0]:-0}" -lt 4 ] && printf 1>&2 '%s: bash version 4 or later required.\n' "${0##*/}" && exit 1;

declare -A pid_array
declare -a uid_array

while read -r pid_owner
do
    pid_array[${pid_owner}]=$((${pid_array[${pid_owner}]} + 1))
done < \
<(  #suppress stderr if examined processes terminate
    exec 2>/dev/null
    for pid in /proc/[0-9]*/status
    do
	while read -r key ruid euid _
	do
	    [[ "${key}" = "Uid:" ]] && printf '%s\n' "${ruid}" && continue
	done < "${pid}"
    done
)

ifs_save="${IFS}"
_name_len=4
IFS=":"
while read -r name _ uid _
do
    uid_array[${uid}]=${name}
    [[ ${#name} -gt ${_name_len} ]] && _name_len=${#name}
done < <(getent passwd)
IFS="${save_ifs}"

printf "%${_name_len}s PROCESSES\n" 'USER'

# ${!array[*]} returns keys of an array as of bash 3.x and above
for pid_key in "${!pid_array[@]}";
do
    printf "%${_name_len}s %d\n" "${uid_array["${pid_key}"]}" "${pid_array[${pid_key}]}";
done
