Kill a Process by Name on Linux with pkill
Kill processes by name with pkill, and use -x to match the whole name. With -f, a shell started with bash -c can match its own pattern and kill itself.
pkill fetcher is meant to stop one service, and it takes down two others whose names start with the same word.
cp /bin/sleep /tmp/fetcher
cp /bin/sleep /tmp/fetcher-old
/tmp/fetcher 300 &
/tmp/fetcher-old 300 &
sleep 0.3
echo "before: $(pgrep -l fetcher | awk '{print $2}' | sort | tr '\n' ' ')"
pkill -x fetcher
sleep 0.3
echo "after pkill -x fetcher: $(pgrep -l fetcher | awk '{print $2}' | tr '\n' ' ')"
bash -c 'sleep 401 & pkill -f "sleep 401"; echo survived'
echo "shell with -f pattern: status $?"
pkill fetcher-oldbefore: fetcher fetcher-old
after pkill -x fetcher: fetcher-old
Terminated
shell with -f pattern: status 143pkill takes the same pattern and options as pgrep: a regular expression matched against the process name, so fetcher matches fetcher-old as well. -x requires an exact match and stops only the process called fetcher, as the pkill manual states. The last pair shows -f matching the command line of the shell that started it, which holds the same text in its bash -c argument, so the shell is terminated before it prints anything and exits with status 143.
Patterns in a script should be anchored, with -x for names and a leading caret for -f. A common trick is to write one letter in brackets, as in pkill -f "[s]leep 401", which still matches the target but not the shell that holds the pattern in its own text. Preview with pgrep -a before running pkill as root.