#!/bin/bash # # proc-count.sh # Simple shell script to report total numbers of processes by name # # Changelog # 2014-03-27 - Nathan Isburgh # * Initial version # # Debug flag? 1=on, 0=off DEBUG=1 # Additional user-customized variables... # # END OF CONFIGURATION VARIABLES # NO MORE EDITS BEYOND THIS POINT # # Functions... # # fail [exit code] [exit message] # # Common exit codes: # 1 - Invalid arguments # 2 - Missing arguments # 3 - Missing software # fail() { cleanup ECODE=${1:-1} EMSG=$2 if [ -n "$EMSG" ] then echo $EMSG > /dev/stderr fi exit $ECODE } succeed() { cleanup exit } cleanup() { # Clean up temp files # Close out logs # Disconnect from remote resources rm -f $TMPFILE return } # # debug "message" # debug() { if [ $DEBUG -eq 1 ] then printf "*** [%s] %s\n" "$(date +%r)" "$1" > /dev/stderr fi } usage() { cat << eof $0 [-f filter]... [-c] email -f filter Only report on "filter" processes - can repeat as necessary -c Generate CSV report ( default TSV ) email Address to send report eof } proc-count() { if [ ${#FILTERS[*]} -eq 0 ] then # If there are no filters supplied by user... ps -Ao comm | tail -n +2 | sort | uniq -c | awk "{print \$2\"$SEP\"\$1}" >> $TMPFILE fi for f in ${FILTERS[*]} do debug "Filter: $f" ps -Ao comm | tail -n +2 | sort | uniq -c | awk "/$f/ {print \$2\"$SEP\"\$1}" >> $TMPFILE done mailx -s "Proc Count" $EMAIL < $TMPFILE } # Main body... FILTERS=() SEP="\t" while getopts ":f:c" opt; do case $opt in f) FILTERS+=($OPTARG) ;; c) SEP=, ;; \?) usage fail 1 "Invalid option: -$OPTARG" ;; :) usage fail 1 "Option -$OPTARG requires an argument." ;; esac done eval EMAIL=\$$OPTIND if [ -z "$EMAIL" ] then usage fail 2 "Please supply an email address for the report" fi TMPFILE=$(mktemp) if [ $? -ne 0 ] then fail 100 "Could not create tmp file" fi proc-count succeed