#!/bin/bash # # proc-count.sh [-f filter]... [-c] email # - Simple process counting tool # # Changelog: # * 2014-05-22 - Nathan Isburgh # - Initial version of script # - Implemented basic counts, filters, and outputs # # Debug flag - 1 for verbose debugging DEBUG=1 # # NO EDITS BELOW THIS LINE # # # succeed() # - gracefully exit from program successfully # succeed() { cleanup exit 0 } # # fail( code, msg ) # - gracefully exit from program in failure state # fail() { cleanup if [ -n "$2" ] then echo "$2" > /dev/stderr fi exit ${1:-1} } # # cleanup() # - clean up log/lock files, etc # cleanup() { return } # # debug( msg ) # - Prints standard debug message to stderr # - Only print if debugging is enabled # debug() { if [ "$DEBUG" -ne 1 ] then return fi echo $(date +%T) " $@" > /dev/stderr } # # usage() # - Print a basic usage statement for user to understand program use # usage() { cat << eof Usage: $0 [-f filter]... [-c] email Sends report of process counts to email -f filter Filter process list by 'filter' -c Produce a CSV report, instead of TSV email Email recipient for the generated reports eof } # # proc-count() # - Heavy lifter for producing process count report and emailing it # to $EMAIL # proc-count() { # Two scenarios: # 1) No filters given, produce full report # 2) Filters given, produce filtered report if [ ${#FILTERS[*]} -eq 0 ] then ps -Ao comm= | sort | uniq -c | awk -v OFS=$SEP '{print $2,$1}' fi for filter in ${FILTERS[*]} do ps -Ao comm= | fgrep $filter | sort | uniq -c | awk -v OFS=$SEP '{print $2,$1}' done } # Main code body # ... SEP="\t" FILTERS=() while getopts ":f:c" opt; do case $opt in f) debug "filter requested: '$OPTARG'" FILTERS+=("$OPTARG") ;; c) debug "CSV output requested" SEP="," ;; \?) usage fail 1 "Invalid option: -$OPTARG" ;; :) usage fail 2 "Option -$OPTARG requires an argument." ;; esac done eval EMAIL=\${$OPTIND} # Make sure the user supplied an email address if [ -z "$EMAIL" ] then usage fail 3 "Please supply an email address for the reports" fi proc-count | mailx -s "Process count" $EMAIL succeed