Bash function to kill a process

I made an alias for this function to kill processes in bash:

In my .bashrc file

kill_process(){ # $1 being a parameter for the process name kill $(ps ax | grep "$1" | awk '{print $1}') } alias kill_process=kill_process 

So, suppose I want to kill the meteor process:

Look at all the meteor shower processes:

 ps aux | grep 'meteor' | awk '{print $2}' 21565 21602 21575 21546 

Call the kill_process function with an alias

 kill_process meteor bash: kill: (21612) - No such process 

So, the kill_process function effectively terminates the meteor processes, but the kill command looks for a nonexistent pid. Please note that pid 21612 not specified ps aux | grep ps aux | grep . Any ideas on improving the kill_process function to avoid this?

+5
source share
2 answers

The standard method of killing processes by name uses killall , as Svojan suggests in his answer.

As for your kill_process function, the grep expression that filters ps will correspond to the grep process itself (you can see that this works with the pipeline without awk ), but by the time kill , this process no longer works. This is the message you see.

Each time you run a command, grep starts again with a new PID: the reason you cannot find it in the list when testing it.

You can:

  • Run ps first, move it to a file or variable, then grep
  • grep PID filter from list
  • (Simpler) supress kill output:

     kill $(...) 2>/dev/null 
+3
source

I think in your case the killall command will do what you want:

 killall NAME 
+4
source

Source: https://habr.com/ru/post/1232877/


All Articles