How to write a shell script to find PID and Kill… here is a solution to the problem.
How to write a shell script to find PID and Kill
I’m trying to write a script to find the PID of another script I ran earlier. Once the PID is found, it sends a stop signal.
I
can find the PID but the kill signal is not processed and I get a return message saying it’s not a PID.
Here’s what I’m doing :
#!/bin/bash
PID=`ps -eaf | grep "start.sh" | awk '{print $2}'`
echo "$PID"
if [[ -z "$PID" ]];
then(
echo "Start script is not running!"
)else(
kill -9 $PID
)fi
The script it tries to kill starts many others, so I hope killing start.sh
will kill all child processes.
Solution
When you run
ps -eaf | grep "start.sh" | awk '{print $2}'
You create a subshell that contains the word start.sh
. grep
will then start its own process and start.sh
process, which will give you two PIDs.
This means when you try to kill start.sh
and
ps -eaf | grep "start.sh" | awk '{print $2}'
Process. start.sh
will die, but the other will no longer exist and therefore cannot be killed, so it gives you an error.
If you’re splitting commands, you’ll probably have better luck:
PIDS=$(ps -eaf)
PID=$(echo "$PIDS" | grep "start.sh" | awk '{print $2}')