Skip to content

Instantly share code, notes, and snippets.

@smondet
Created November 11, 2015 18:11
Show Gist options
  • Save smondet/7345ba91783688679fb0 to your computer and use it in GitHub Desktop.
Save smondet/7345ba91783688679fb0 to your computer and use it in GitHub Desktop.
Kill Stuff by name
#!/bin/bash
#
# Copyright (c) 2006 by Sebastien Mondet.
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
SCRIPT_NAME=$(basename $0)
short_usage()
{
echo "Cf : $SCRIPT_NAME [--help]"
}
long_usage()
{
echo ""
echo "User Commands $SCRIPT_NAME"
echo ""
echo "Description : send signals with regexps"
echo
echo "Usage :"
echo "-----"
echo " $SCRIPT_NAME {--help,-h}"
echo " $SCRIPT_NAME [-f] [-9] [-g pattern1] [pattern2] ..."
echo ""
echo "Options :"
echo "-------"
echo " --help | -h : show this help message"
echo " -f : force (no question)"
echo " -9 : use -9 for 'kill'"
echo " -g pattern : egrep pattern"
echo " (each arg without option is considered as a '-g' one)"
echo ""
}
KILL_FLAGS=""
FORCE_FLAG=0
GREP_COUNT=0
GREP_PTNS=""
PID_COUNT=0
PID_NBS=""
if [ "$1" = "--help" ]
then
long_usage ;
exit
fi
if [ $# -eq 0 ]
then
short_usage ;
exit
fi
while getopts h9g:f option
do
case $option in
9 ) KILL_FLAGS="$KILL_FLAGS -9" ;;
f ) FORCE_FLAG=1 ;;
h ) long_usage ; exit ;;
g ) GREP_COUNT=$(($GREP_COUNT + 1)) ; GREP_PTNS[$GREP_COUNT]=$OPTARG ;;
\?) short_usage ; exit 2 ;;
esac
done
shift `expr $OPTIND - 1`
if [ $# -ne 0 ] ; then
for arg in $*; do
GREP_COUNT=$(($GREP_COUNT + 1)) ; GREP_PTNS[$GREP_COUNT]=$arg ;
done
fi
KILL_CMD_LINE="kill $KILL_FLAGS "
TMP_FILE=/tmp/skill_$$
while [ $GREP_COUNT -ne 0 ]
do
TMP_GREP=${GREP_PTNS[$GREP_COUNT]}
ps aux | egrep $TMP_GREP | grep -v "grep" | grep -v 'skill'\
> $TMP_FILE
if [ $(cat $TMP_FILE | wc -l) -eq 0 ]
then
echo "No PID found for : $TMP_GREP"
fi
PIDS=$( cat $TMP_FILE | awk '{ print $2 }' )
for i in $PIDS
do
ANSW="_"
if [ $FORCE_FLAG -eq 0 ]
then
echo "Do you want to kill :"
cat $TMP_FILE | grep $i
# POTENTIAL BUG : $i's father cat appear there...
printf "[y/n]? "
read ANSW
fi
if [ "$ANSW" = "y" ] || [ $FORCE_FLAG -ne 0 ]
then
$KILL_CMD_LINE $i
echo $KILL_CMD_LINE $i
else
echo "$i will survive"
fi
done
GREP_COUNT=$(( $GREP_COUNT - 1 ))
done
rm -f $TMP_FILE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment