#!/bin/bash # # proc-count.sh # - Counts processes by filter, producing configurable report # # Changelog # 2014-05-01 - Nathan Isburgh # * Initial version # # Debug - 1 = on, 0 = off DEBUG=1 # # NO EDITS AFTER THIS LINE # # # fail ecode msg # - gracefully exit with ecode and printing optional msg # fail() { cleanup if [ -n "$2" ] then echo $2 > /dev/stderr fi exit ${1:-1} } # # succeed # - cleanup and exit 0 # succeed() { cleanup exit 0 } # # cleanup # - clean up after script ( remove tmp files, etc ) # cleanup() { return } # # debug msg # - print msg to stderr with simple timestamp # debug() { if [ "$DEBUG" -eq 1 ] then echo $(date +%T) $@ fi } # # usage # - Print simple usage/synopsis type message to stdout # usage() { cat << eof proc-count.sh [-f filter]... [-c] email Email process count report in TSV format Options -f filter Apply search filter to limit report results -c Produce CSV results email Recipient for the report eof } mail-proc-count() { if [ ${#FILTERS[*]} -eq 0 ] then ps -Ao comm | sort | uniq -c | awk -v OFS=$SEP '{print $2,$1}' else for f in ${FILTERS[*]} do ps -Ao comm | fgrep $f | sort | uniq -c | awk -v OFS=$SEP '{print $2,$1}' done fi | mailx -s "Process Count" $EMAIL } # Main body SEP="\t" FILTERS=() # Process command line arguments... while getopts ":f:c" opt; do case $opt in f) FILTERS+=($OPTARG) ;; c) SEP=, ;; \?) fail 1 "Invalid option: -$OPTARG" ;; :) fail 1 "Option -$OPTARG requires an argument." ;; esac done debug "\$@: '$@' \$OPTIND: $OPTIND \$#: $#" eval EMAIL=\${$OPTIND} debug "\$EMAIL: $EMAIL" debug "Number of FILTERS: ${#FILTERS[*]}" debug "\$FILTERS: '${FILTERS[*]}'" # Additional argument checks.. if [ $# -eq 0 ] then usage fail fi mail-proc-count succeed