Home > Linux How to, Pro Linux > Linux kill multiple process with a single command

Linux kill multiple process with a single command

November 28th, 2011 Leave a comment Go to comments

processes 150x150 Linux kill multiple process with a single command Sometimes it can be useful to kill multiple processes with a single command, while using a combination of ps and grep can help you hunt down the process you need and to kill it this is not the easiest or fastest  approach if you need to kill a large number of processes. Let’s see how to do this.

The first step would be getting a list of the interesting processes we need to kill, in this example I will use the NFS daemon, which can easily be accomplished with a command similar to the following :

 ps -ef  | grep nfs 


The command on my system produced the following output :

 ps -ef | grep nfs
root      1873     2  0 08:50 ?        00:00:00 [nfsd4]
root      1874     2  0 08:50 ?        00:00:00 [nfsd4_callbacks]
root      1875     2  0 08:50 ?        00:00:00 [nfsd]
root      1876     2  0 08:50 ?        00:00:00 [nfsd]
root      1877     2  0 08:50 ?        00:00:00 [nfsd]
root      1878     2  0 08:50 ?        00:00:00 [nfsd]
root      1879     2  0 08:50 ?        00:00:00 [nfsd]
root      1880     2  0 08:50 ?        00:00:00 [nfsd]
root      1881     2  0 08:50 ?        00:00:00 [nfsd]
root      1882     2  0 08:50 ?        00:00:00 [nfsd]
root      4835  4554  0 18:43 pts/0    00:00:00 grep nfs

Ok we can see the full list of processes bound to NFS together with other information we actually don’t need, what is really interesting for us is PID of the process which is exposed in the second column of the output so let’s call awk to help us in the task :

 ps -ef | grep nfs | awk '{print $2}' 

The above command will list all processes on the system bout to NFS but this time instead of printing everything  it will print on screen only the content of the second output column which again on my system looks like :

 ps -ef | grep nfs | awk '{print $2}'
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
4871

Ok we’re almost there, now let’s put all together and let’s kill all the processes  with the command :

  kill `ps -ef | grep nfs | awk '{print $2}'` 

That’s it all the processes that results from our expression will be killed with the single command, that is even easy to script when you often need to kill processes on a server (I keep a copy of it on one of my lab machines where I often run a script that launches 100+ instances of the same program and need to kill them all).

I hope you will find the article interesting and useful and would appreciate if you could take the time to retweet or share it.

Cheers Lethe.

VN:F [1.9.20_1166]
Rating: 5.0/5 (2 votes cast)
Linux kill multiple process with a single command, 5.0 out of 5 based on 2 ratings

Incoming search terms:

Categories: Linux How to, Pro Linux