#!/bin/bash # # kill-thread.sh [options] # - Kill database connections based on options # # Changelog: # * 2014-05-23 - Nathan Isburgh # - Initial version of script # # 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 [-u user] [-h host] [-d db] [-c command] Kill database connections based on one or more attributes -u user Kill by connected user -h host Kill connections from host -d db Kill connections to database db -c command Kill connections currently executing command eof } kill-thread() { # 3 root localhost mysql mysql -se "show full proCESslIst" | fgrep -v proCESslIst | awk -F'\t' '$2 ~ /'$FUSER'/ && $3 ~ /'$FHOST'/ && $4 ~ /'$FDB'/ && $8 ~ /'$FCMD'/ {print $1}' | xargs -rn 1 mysqladmin kill } # Main code body # ... FUSER='' FHOST='' FDB='' FCMD='' while getopts ":u:h:d:c:" opt; do case $opt in u) debug "user filter requested: '$OPTARG'" FUSER="$OPTARG" ;; h) debug "host filter requested: '$OPTARG'" FHOST="$OPTARG" ;; d) debug "db filter requested: '$OPTARG'" FDB="$OPTARG" ;; c) debug "command filter requested: '$OPTARG'" FCMD="$OPTARG" ;; \?) usage fail 1 "Invalid option: -$OPTARG" ;; :) usage fail 2 "Option -$OPTARG requires an argument." ;; esac done kill-thread succeed