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 mor
You don't need to use an array if you're going to immediately iterate over the results and perform an action:
for pid in $(ps -fe | grep '[p]rocess' | grep -v grep | awk '{print $2}'); do
kill "$pid"
done
Notice we have to exclude grep
's pid from the list of processes to kill. Or we could just use pgrep(1)
:
for pid in $(pgrep '[p]rocess'); do
kill "$pid"
done
If you actually needed to store the pids in an array, pgrep
is how you would do it:
pids=( $(pgrep '[p]rocess') )
Back to killing process. We can still do better. If we're just using pgrep
to get a list of processes to kill them, why not go straight for pgrep
's sister program: pkill(1)
?
pkill '[p]rocess'
As it turns out, no need for bash
scripting at all.