#!/bin/bash
#
CMD=$(basename $0)
CMDVER="1.0"
CMDSTR="$CMD v$CMDVER (2019/03)"

set -e -u

usage()
{
	echo "
=== $CMDSTR == shows top file usage per process, with limits ===

usage: $CMD
" >&2
	exit 1
}

# (MAIN)

[ $# != 0 ] && usage

lsof +c 0 -n 2>/dev/null | awk '{print $1,$2}' \
	| sort | uniq -c | sort -nr | head -25 \
	| while read nr name pid
do
	limits=$(cat /proc/$pid/limits | grep 'open files' | awk '{print $5}')
	printf "%10d / %-10d %-30s (PID %5s)\n" $nr $limits $name $pid
done

exit 0
