Dymond
Dymond

Reputation: 2277

kill multiple process at once works only manually not from inside script

I'm trying to kill multiple process at the same time. Im using this simple for loop to kill the process by PID number.

for i in $(ps -ejH | grep omn_bdxtrc|awk '{print $1}'); do kill ${i}; done

The loop works fine if I enter it manually in the terminal. but if I want to us it from inside an file (*.sh) it returns this output.

/functions.sh: line 231: kill: 25211
25698
27930
8477
5018
16383
13488
2403
10963 18796: arguments must be process or job IDs

have tried multiple ways that works manually, but not from the file.

Any ideas why this is happening?

Thanks in advance.

Upvotes: 0

Views: 642

Answers (1)

Jiri Valenta
Jiri Valenta

Reputation: 550

It looks like the PIDs are being passed as a single argument delimited by line breaks, which kill does not seem to like.

I would simplify the approach by removing the loop completely and just passing the PIDs to kill via xargs:

ps -ejH | grep omn_bdxtrc | awk '{print $1}' | xargs kill

Alternatively (if you don't have or don't want to use xargs for some reason), you can keep your current loop and just sanitize the output from awk by changing all possible line breaks to spaces using tr:

for i in $(ps -ejH | grep omn_bdxtrc | awk '{print $1}' | tr '\n' ' '); do kill ${i}; done

But this is not that elegant.

Probably the most elegant solution would be to use killall, assuming you know the exact name of the process:

killall omn_bdxtrc

Or if you don't know the exact name and need to match a part of it:

killall --regexp '.*omn_bdxtrc.*'

Upvotes: 3

Related Questions