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
pkill [-f] <name>
– jordanm Jun 25 '21 at 15:30for
block exits with 0 if thein
list expands to empty, you may want to set a variable in the loop to record it ran at least once or store PIDs in an array and check its number of elements; 2)xargs
has a-r
option that prevents it from running commands if it receives and empty input. – fra-san Jun 25 '21 at 15:50pkill
not killing child processes. I can't really see how your code would kill child processes either as you never try to resolve relationships between processes. – Kusalananda Jun 25 '21 at 18:02pkill name
(without- 9
) first, to give name a chance, thenpkill -9 name
– Archemar Jun 25 '21 at 19:28