quarks
quarks

Reputation: 35276

Automate Killing of Matching Processes with Bash

I need to create a script (.sh) that I can use to kill processes in one command.

When I do $ pgrep -f vmware

It shows a list of:

2234
2241
2251
2296
4751

Now I need to do for each one sudo kill -9 4751

Is there a way to automate this into

sh sudokiller.sh vmware then it will do the task automatically? Or there's a better approach?

Upvotes: 0

Views: 157

Answers (2)

TimP
TimP

Reputation: 210

You want pkill; it has pretty much the exact same command line options as pgrep:

$ pkill -?
Usage: pkill [-SIGNAL] [-fvx] [-n|-o] [-P PPIDLIST] [-g PGRPLIST] [-s SIDLIST]
    [-u EUIDLIST] [-U UIDLIST] [-G GIDLIST] [-t TERMLIST] [PATTERN]

In fact, on my system (Slackware 14.1) /usr/bin/pgrep is actually a symlink to /usr/bin/pkill, that searches when run as pgrep, and kills when run as pkill.

Example:

me@host:~$ pgrep -f test.sh
1927
1932
1937
1945
1950
1955
1960
1965
1970
1975
1980
me@host:~$ pkill -f test.sh
me@host:~$ pgrep -f test.sh
me@host:~$

Upvotes: 3

choroba
choroba

Reputation: 241898

Use a loop:

for pid in `pgrep -f vmware` ; do
    sudo kill -9 $pid
done

Or, just use

sudo killall -9 vmware

Upvotes: 2

Related Questions