2020/04/30

bash script to kill a process based on partial name

why you might need this: because sometimes some processes can't simply terminated using the GUI. And after too many years typing ps -A | grep something then kill -9 the id, I decided to write a script to avoid having to type two commands.

Be warned, this will only kill the first process found with the lowest process ID.

it takes only one argument as the partial name to be looked upon the ps -A command.
#!/bin/bash
proc=$(ps -A |grep $1 | head -n 1)
if [ -z "$proc" ] ; then
   echo Error: no processes found with the given partial name!
   exit 1
fi
echo ps -A says:
echo $proc
procid=$( echo "$proc" |grep "[0-9]*" -o |head -n 1)

echo "kill? <Y/N>"
read answer
if [ "$answer" != "${answer#[Yy]}" ] ;then
    echo Yes
    kill -9 $procid
    echo Testing if the process is still alive ...
    isdead=$(ps -A |grep "$proc")
    [ -z "$isdead" ] && echo Process has been terminated! || echo process is still alive !?
else
    echo No!
fi
you can replace the question with the actual command but I don't recommend it.

No comments:

Post a Comment