Home > HowTo's > Zapping processes in Bash

Zapping processes in Bash

January 24th, 2009 Leave a comment Go to comments

The following is a handy little script I wrote which politely asks a collection of matching processes to exit. After a second the process is forcibly killed.

This command is designed as a drop-in replacement for the slightly cryptic pgrep and pkill commands.

?Download zap.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
zap() {
	# Usage: zap [SIGNAL|-NUMERIC|shoot] <fgrep>
	SIGNAL=''
	case "$1" in
		shoot|-0) SIGNAL='SHOOT';;
		term|-15) SIGNAL='TERM';;
		kill|-9) SIGNAL='KILL';;
		hup|-1) SIGNAL='HUP';;
	esac
	if [ "$SIGNAL" != '' ]; then
		shift
	else
		SIGNAL='SHOOT'
	fi
	PROCS=`ps ax -eo pid,comm | fgrep "$1"`
	MODE=0
	for DATA in $PROCS; do
		if [ "$MODE" -eq 0 ]; then
			PID="$DATA"
			MODE=1
		else
			CMD="$DATA"
			MODE=0
			if [ "$SIGNAL" == 'SHOOT' ]; then
				echo -n "Shooting #$PID - $CMD..."
				kill $PID
				sleep 1
				kill -9 $PID
				echo "Shot"
			else
				echo -n "Killing #$PID - $CMD..."
				kill $SIGNAL $PID
				echo "Killed"
			fi
		fi
	done
}

To install it simply dump the above text inside your existing ~/.bashrc file.

Usage is quite simple:

To politely kill all processes (then force-killing if it still does not die) containing the string ‘gnome':

1
zap gnome

To just kill-forcefully:

1
zap -9 gnome
Categories: HowTo's Tags:
  1. No comments yet.
  1. No trackbacks yet.
*