#!/bin/bash # killall--Sends the specified signal to all processes that match a # specific process name. # By default it only kills processes owned by the same user, unless # you're root. Use -s SIGNAL to specify a signal to send to the process, # -u USER to specify the user, -t TTY to specify a tty, # and -n to only report what should be done, rather than doing it. setglobal signal = '"-INT'" # Default signal is an interrupt. setglobal user = '',"" tty = '',"" donothing = '0' while getopts "s:u:t:n" opt { match $opt { # Note the trick below: the actual 'kill' command wants -SIGNAL # but we want SIGNAL, so we'll just prepend the '-' below. with s setglobal signal = ""-$OPTARG""; with u if test ! -z $tty { # Logic error: you can't specify a user and a tty device echo "$0: error: -u and -t are mutually exclusive." > !2 exit 1 } setglobal user = $OPTARG; with t if test ! -z $user { echo "$0: error: -u and -t are mutually exclusive." > !2 exit 1 } setglobal tty = $2; with n setglobal donothing = '1'; with ? echo "Usage: $0 [-s signal] [-u user|-t tty] [-n] pattern" > !2 exit 1 } } # Done with processing all the starting flags with getopts... shift $shExpr(' $OPTIND - 1 ') # If the user doesn't specify any starting arguments (earlier test is for -?) if test $Argc -eq 0 { echo "Usage: $0 [-s signal] [-u user|-t tty] [-n] pattern" > !2 exit 1 } # Now we need to generate a list of matching process IDs, either based on # the specified tty device, the specified user, or the current user. if test ! -z $tty { setglobal pids = $[ps cu -t $tty | awk "/ $1$/ { print \$2 }] } elif test ! -z $user { setglobal pids = $[ps cu -U $user | awk "/ $1$/ { print \$2 }] } else { setglobal pids = $[ps cu -U $(USER:-LOGNAME) | awk "/ $1$/ { print \$2 }] } # No matches? That was easy! if test -z $pids { echo "$0: no processes match pattern $1" > !2; exit 1 } for pid in [$pids] { # Sending signal $signal to process id $pid: kill might still complain # if the process has finished, the user doesn't have permission to kill # the specific process, etc., but that's okay. Our job, at least, is done. if test $donothing -eq 1 { echo "kill $signal $pid" # the –n flag: "show me, but don't do it" } else { kill $signal $pid } } exit 0