0

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
acgbox
  • 941
  • 3
    This can be done with pkill [-f] <name> – jordanm Jun 25 '21 at 15:30
  • it works in some scenarios, but in others there are child processes that do not close – acgbox Jun 25 '21 at 15:35
  • Not an answer, because I don't think I'm understanding the overall goal (e.g. how is filtering processes by part of their command line going to kill children?), but: 1) a for block exits with 0 if the in 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:50
  • great for the clarification of xargs. But the problem is presented in the "second option" – acgbox Jun 25 '21 at 15:57
  • 1
    The "second option" won't work how you think - see Pass shell variable as a /pattern/ to awk – steeldriver Jun 25 '21 at 16:24
  • thanks for the clarification of /pattern/ to awk (does not accept variables) – acgbox Jun 25 '21 at 16:40
  • You commented something about pkill 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:02
  • @Kusalananda That's why you just said that I asked my question. Because I'm not sure if it really does. If you have an answer, post it – acgbox Jun 25 '21 at 18:18
  • I would try pkill name (without - 9) first, to give name a chance, then pkill -9 name – Archemar Jun 25 '21 at 19:28

0 Answers0