Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the PID(s) of running processes and store as an array

Tags:

arrays

linux

bash

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.

like image 957
user3255401 Avatar asked Jan 31 '14 00:01

user3255401


1 Answers

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

like image 132
SparkyRobinson Avatar answered Sep 22 '22 17:09

SparkyRobinson