0

I'm trying to create a script that will kill a process and confirm the process is running before issuing the kill -9 command, I'm running into a bug where it always assumes there is output.

#!/bin/sh
rc=$?

#Ask to check for a process to kill
clear
echo "Please enter a process number you would like to kill"
echo ""
read proc
ps -ef | awk '{print $2}' | grep *$proc*
if [[ $rc != 0 ]]; then
        echo "Process not running or already killed"
        sleep 2
        exit $rc
else
        clear
        echo "Killing process..."
        sleep 2
#       kill -9 $proc
fi

1 Answers1

1

Using grep $proc is wrong. If you want to kill PID 22, it will match 122, 220, etc.

The simplest way to test if a PID exists is to try to send signal 0 to it:

if kill -0 "$proc" 2>/dev/null
then
    clear
    echo "Killing process..."
    sleep 2
    kill -9 "$proc"
else
    clear
    echo "Process not running or already killed"
    sleep 2
    exit 1
fi

Signal 0 doesn't do anything, it just tests whether you're able to send signals to that process.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Actually, the simplest way is to check for the PID directory in /proc as this does not involve any signalling or spawning of additional processes. `if [ -d /proc/$proc ]; then` – Geoffrey Jul 24 '13 at 17:09
  • 1
    @Geoffrey True, although that's more OS-specific. I know this is tagged linux, but a solution that's portable to just about every flavor of Unix seems cleaner to me. You could send this script back 20 years and it will probably work. – Barmar Jul 24 '13 at 17:11