Zaki Madridista
Zaki Madridista

Reputation: 1

Killing a procces with a given name and display the PID

so here I have an essay and I need to make a command where I kill all process with a given name then when I enter it it will display the pid of the process's with that name and then kill it and I need to use tr -s , cut ,
for now this is what I did

echo " What do you want to kill? "
read pr
ps -fA| grep -c $pr | grep -v grep | kill -9 $(ps aux | grep -e $pr | awk '{print $2}')

Upvotes: 0

Views: 47

Answers (1)

Niall Cosgrove
Niall Cosgrove

Reputation: 1303

for i in $(ps -ef |grep $pr |grep -v grep |tr -s ' ' |cut -f2 -d' ')
    do
        kill $i && echo killed $i
    done

The tr -s ' ' will squeeze repeated spaces into one space which cut can use as a field separator.

Its better and easier to use pgrep

i.e

kill $(pgrep $pr) && echo done || echo not done

Here is the man page: man pgrep

Upvotes: 1

Related Questions