views:

124

answers:

3

I am trying write a shell script that will kill all processes that are running that match a certain pattern, then restart them. I can display the processes with:

ps -ef|grep ws_sched_600.sh|grep -v grep|sort -k 10

Which gives a list of the relevent processes:

user 2220258       1   0 16:53:12      -  0:01 /bin/ksh /../../../../../ws_sched_600.sh EDW02_env
user 5562418       1   0 16:54:55      -  0:01 /bin/ksh /../../../../../ws_sched_600.sh EDW03_env
user 2916598       1   0 16:55:00      -  0:01 /bin/ksh /../../../../../ws_sched_600.sh EDW04_env

But I am not too sure about how to pass the process ids to kill?

A: 

I think this is what you are looking for

for proc in $(ps -ef|grep ws_sched_600.sh|sort -k 10)
do
    kill -9 proc
done

edit:

Of course... use xargs, it's better.

Cambium
`kill: Illegal number: proc`
msw
+1  A: 

The sort doesn't seem necessary. You can use awk to print the second column and xargs to convert the output into command-line arguments to kill.

ps -ef | grep ws_sched_600.sh | awk '{print $2}' | xargs kill

Alternatively you could use pkill or killall which kill based on process name:

pkill -f ws_sched_600.sh
John Kugelman
Why the sort? You're going to kill them anyways.
zneak
no need grep and xargs as well. ps -ef | awk '/ws_sched_600/{cmd="kill -9 "$2;system(cmd)}
ghostdog74
+1  A: 
pkill ws_sched_600.sh

If you are concerned about running your command on multiple platforms where pkill might not be available

ps -ef | awk '/ws_sched_600/{cmd="kill -9 "$2;system(cmd)}
ghostdog74
`pkill` doesn't exist on Mac OS at least (it's `killall` here).
zneak
I think this should work. Have not used AWK much but need to start!
pharma_joe