Skip to content

Instantly share code, notes, and snippets.

@florido
Created October 24, 2018 06:48
Show Gist options
  • Select an option

  • Save florido/a571335f2288f2091355453db8789e9a to your computer and use it in GitHub Desktop.

Select an option

Save florido/a571335f2288f2091355453db8789e9a to your computer and use it in GitHub Desktop.
Kills all processes belonging to a specific user while iterating signals.
#! /bin/bash
#
# TITLE: killuser
# AUTHOR: Josef Gosch <[email protected]>
# DESCRIPTION: Kills all processes belonging to a specific user.
# Iterates signals while doing so, with a 3 second break.
# Signal order: SIGHUP, SIGTERM, SIGINT, SIGKILL
# VERSION: 1.0
function die {
message=$1
echo -e "$0: $message"
exit 1
}
usage=" Kill all processes belonging to a specific user.\n USAGE: $0 USERNAME"
pkill=`which pkill` || die "Command 'pkill' not found."
pgrep=`which pgrep` || die "Command 'pgrep' not found."
user=$1
if [ -z "$user" ]; then
die "$usage"
fi
for signal in HUP TERM INT KILL; do
pids=`$pgrep -u $user`
pcount=`echo $pids | wc -w`
if [ -z "$pids" ]; then
break
fi
echo "sending SIG$signal to $pcount processes: "$pids
$pkill -SIG$signal -u "$user"
if [ "$signal" = "KILL" ]; then
sleep 1
else
sleep 3
fi
done
remaining=`$pgrep -u $user | wc -w`
if [ $remaining -eq 0 ]; then
echo "All processes killed."
exit 0
else
echo -e "Failed to kill $remaining processes: "`$pgrep -u $user`
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment