I have these attempts to shut down processes (and childs) by name (I got both from this site and adapted them):
read -p "Set process name: " PS
# first option
f() { ps ax | grep "$1" | grep -v grep | awk '{print $1}' | xargs kill -9; }
f $PS
# second option
for pid in $(ps -ef | awk '/$PS/ {print $2}'); do kill -9 $pid; done
# end of bash
if [ $? -gt 0 ]; then
echo "no process:" $PS
else
echo "Finished"
fi
But I don't know which of the two is more effective (or none of the above)
Additionally, the second loop does not complete (that is, if there are no processes, it should exit "no process:" name of process), but it goes straight to "Finished"
And in both cases there is a problem with kill command. If there are no processes, a message appears indicating options on the use of kill. I can hide it with &> /dev/null or set +m, set -m but but I don't know if kill will have any flag (switch) to silence the output
Update:
thanks to @steeldriver I was able to see the error that awk does not accept variables (/$PS/) so i found this solution HERE:
And replace this:
for pid in $(ps -ef | awk '/$PS/ {print $2}'); do kill -9 $pid; done
with this:
for pid in $(ps -ef | grep "$PS" | awk '{print $2}'); do kill -9 $pid; done