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 Answers 3

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.

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

2
  • Related: Why should I not use 'kill -9' / SIGKILL Commented Sep 11, 2020 at 5:59
  • @Kusalananda, I did say kill all command and what signal you want to send. Or he can leave off the signal and I believe the default is sending a SIGTERM, but I believe when the operating system is closing down I think it sends out SIGTERM and waits and then sends out a SIGKILL. I will modify my answer and replace 9 with <signal>. Commented Sep 11, 2020 at 16:27
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'

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.