I made an alias for this function in order to kill processes in bash:
On 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:
Let's see all meteor processes:
ps aux | grep 'meteor' | awk '{print $2}'
21565
21602
21575
21546
Calling the kill_process
function with the alias
kill_process meteor
bash: kill: (21612) - No such process
So, the kill_process
function effectively terminates the meteor
processes, but it's kill
command looks for an inexistent pid. Notice the pid 21612
wasn't listed by ps aux | grep
. Any ideas to improve the kill_process
function to avoid this?
You can use the command pkill to kill processes. If you want to "play around", you can use "pgrep", which works exactly the same but returns the process rather than killing it. pkill has the -f parameter that allows you to match against the entire command. So for your example, you can: pkill -f "gedit file.txt".
We can use “ps augx” to list all processes and the locate those with keyword by using “grep keyword” command. Next, we need to split each line by whitespace delimiter and list the second column which is the process ID. Finally, we feed into xargs command to kill them. Here is the little BASH Script that does the job well.
A Bash process is simply an executable which is running. For example, when you start the calculator in your desktop environment, a Bash process is created. Such a bash has two main process identifiers, namely the PID and the PPID, the Process Identifier, and the Parent Process Identifier.
At Linux, sometimes we want to search all the processes that contain some name and then terminate all of them. We can use “ps augx” to list all processes and the locate those with keyword by using “grep keyword” command. Next, we need to split each line by whitespace delimiter and list the second column which is the process ID.
I think in your case the killall command would do what you want:
killall NAME
The standard way of killing processes by name is using killall
, as Swoogan suggests in his answer.
As to your kill_process
function, the grep
expression that filters ps
will match the very own grep
process (you can see this running the pipeline without awk
), but by the time kill
is invoked, that process is no longer running. That's the message you see.
Each time you run the command, grep
runs again with a new PID: that's the reason you can't find it on the list when you test it.
You could:
ps
first, pipe it into a file or variable, then grep
grep
's PID out of the list(Simpler) supress kill
output:
kill $(...) 2>/dev/null
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With