Ladies and gentlemen, presenting: kgrep – kill-grep
This is a bash function which allows you to type in a search term and kill matching processes. You will be prompted to kill each matching process for your searchterm.
You can also optionally provide a specific signal to use for the kill commands (default: 15)
Usage: kgrep [<signal>] searchterm
Signal may be -2, -9, or -HUP (this could be generalised but I CBF).
search term is anything grep recognises.
kgrep() {
#grep for processes and prompt whether they should be killed
if [ -z "$*" ]; then
echo "Usage: $0 [-signal] searchterm"
echo -e "\nSearches for processes matching and prompts to kill them."
echo -e "signal may be:\n\t-2\n\t-9\n\t-HUP\n to send a different signal (default: TERM)"
return 0
fi
SIG="-15"
#yes, this could be more sophisticated
if [ "$1" == "-9" ] ||
[ "$1" == "-2" ] ||
[ "$1" == "-HUP" ]; then
SIG="$1"
shift
fi
#we need to unset the field separator if ^C is pressed:
trap "unset IFS; return 0" KILL
trap "unset IFS; return 0" QUIT
trap "unset IFS; return 0" INT
trap "unset IFS; return 0" TERM
IFS=$'\n'
for l in `ps aux | grep "$*" | grep -v grep `; do
echo $l
pid=`echo $l | awk '{print $2}'`
read -p "Kill $pid (n)? " a
if [[ "$a" =~ [Yy]([Ee][Ss])? ]]; then
echo kill $SIG $pid
kill $SIG $pid
fi
done
unset IFS
}