Skip to content

Instantly share code, notes, and snippets.

@tsaavik
Created August 9, 2016 16:25
Show Gist options
  • Save tsaavik/6b79c608e848fd83876d9dcd9fa74a38 to your computer and use it in GitHub Desktop.
Save tsaavik/6b79c608e848fd83876d9dcd9fa74a38 to your computer and use it in GitHub Desktop.
Old Process Killer - Finds the passed process name that has been running longer than 24 hours and kills it
#!/bin/bash
# Check for user input
process=$@
if [[ -z "${process}" ]] ;then
echo "This program requires a process name."
echo "The (oldest) given process name will be killed"
echo "if it has been running for > 24 hours"
exit 1
fi
# get oldest matching pid (-o) with full commandline name match (-f)
processpid=$(pgrep -f -o "${process}")
# Check that we got a pid, exit sucessfully if we don't.
if [[ ${processpid} = *[^0-9]* ]] || [[ -z "${processpid}" ]] ;then
#echo "(${processpid}) is empty or a non-digit value"
exit 0
fi
# From man ps
# start_time START starting time or date of the process. Only the year will be displayed if
# the process was not started the same year ps was invoked, or "MmmDD" if it
# was not started the same day, or "HH:MM" otherwise. See also
# bsdstart, start, lstart, and stime.
processstart=$(ps --no-headers -o start_time ${processpid})
# so we should only have ##:##:## in this variable (if it is under 24 hours old)
if [[ ${processstart} = *[^0-9\:]* ]] ;then
#echo "(${processstart}) is not in HH:MM:SS format, must be older then 24 hours"
#read -p "press enter to kill pid"
/bin/kill -9 ${processpid}
#echo "killed ${processpid}"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment