1

I have many processes running by name gunicorn

ubuntu   23884  0.0  7.1 190092 71980 ?        S    Sep10   0:01 gunicorn: worker [ll1]
ubuntu   23885  0.0  6.8 187120 69128 ?        S    Sep10   0:01 gunicorn: worker [ll1]
ubuntu   23886  0.0  7.1 189800 71712 ?        S    Sep10   0:01 gunicorn: worker [ll1]

I want to kill all proccess by name gunicorn.Currently i am able to kill only one process by this script at a time.

#!/bin/bash
pid=`ps ax | grep gunicorn | awk '{split($0,a," "); print a[1]}' | head -n 1`
echo $pid
kill $pid
echo "killed gunicorn"

3 Answers3

4
pkill -f gunicorn
echo "killed gunicorn"

That will kill any process that has the name gunicorn on the line and print the killed gunicorn message.

Nasir Riley
  • 11,422
2

You can use the kill all command and what signal you want to send:

killall -<signal> gunicorn

You can also use -v to output more information of what it is doing:

killall -v -<signal> gunicorn

Or to use a script like you are doing you could do something like this:

#!/bin/bash

for pid in pidof gunicorn; do kill -<signal> $pid; echo "killed gunicorn [$pid]"; done

<signal>:

enter image description here

NiteRain
  • 308
1

There are many way to do this but let's focus on the main two that I know:

Using ps and xargs

With grep:

ps -ef | grep '<pattern>' | grep -v grep | awk '{print $2}' | xargs -r kill -9

With awk:

ps -ef | awk '/<pattern>/ && !/awk/ {print $2}' | xargs -r kill -9

These commands will kill all the process that match with the <pattern>

So your script will be like:

#!/bin/bash
ps -ef | grep 'gunicorn' | grep -v grep | awk '{print $2}' | xargs -r kill -9

[ $? -eq 0 ] && echo 'killed gunicorn'

Or,

#!/bin/bash
ps -ef | awk '/gunicorn/ && !/awk/ {print $2}' | xargs -r kill -9

[ $? -eq 0 ] && echo 'killed gunicorn'

Using ps and for

for pid in `ps ax | grep '<pattern>' | awk ' { print $1;}'`; do 
  kill -9 $pid
done

This also will kill all the process that match with the <pattern>

So your script will be like:

#!/bin/bash

for pid in ps ax | grep 'gunicorn' | awk ' { print $1;}'; do kill -9 $pid done

[ $? -eq 0 ] && echo 'killed gunicorn'

Teocci
  • 151