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

arrays, bash, linux

Solution

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

Problem

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.

Original source