Pgrep returns mutiple PIDs
I had to tackle this same problem a couple of weeks ago. pgrep
and pkill
support extended regular expressions so it's a simple matter of getting the right regexp.
This is your script with the regexp that I used.
#!/bin/bash
ProcessName=$1
pID= pgrep -fl "^(/.*)?${ProcessName}\s"
echo $pID
Although using pkill
(as Caleb suggested) is better.
pkill -fl "^(/.*)?${ProcessName}\s"
You may still need to tweak the regexp to get the desired results for your use case and how the program is being executed.
Now, if there are actually multiple processes running with that name they will of course be killed. If you want to avoid that you can use -o
to kill only the oldest matching process or -n
to kill only the newest. If you want only one, but neither the oldest or newest then you probably shouldn't be using p(kill|grep)
.