I'm trying to write a bash script to find the PID of a running process then issue a kill command. I have it partially working, but the issue I face is that there may be more than one process running. I want to issue a kill command to each PID found.
I presume I need to put each PID in to an array but am at a loss as to how to do that.
What I have so far:
pid=$(ps -fe | grep '[p]rocess' | awk '{print $2}')
if [[ -n $pid ]]; then
echo $pid
#kill $pid
else
echo "Does not exist"
fi
What this will do is return all PIDs on a single line, but I can't figure out how to split this in to an array.
Here's a little one liner that might help
for pid in `ps -ef | grep your_search_term | awk '{print $2}'` ; do kill $pid ; done
Just replace your_search_term with the process name you want to kill.
You could also make it into a script and swap your_search_term for $1
EDIT: I suppose I should explain how this works.
The back ticks `` collects the output from the expression inside it. In this case it will return a list of pids for a process name.
Using a for loop we can iterate through each pid and kill the process.
EDIT2: replaced kill -9 with kill
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With