xargs command to kill process

Xargs Command to Kill Process

Xargs is a very useful Linux command that allows you to automatically create and run other commands. It is a great tool to build execute commands from standard input. It basically uses its own command line arguments as arguments for the built command. In this article, we will learn how to create xargs command kill process.

Xargs Command to Kill Process

Xargs has a slightly complicated syntax so we will construct the command in a step by step manner.

First we need the PIDs of processes to be killed. For this purpose, we will ps aux command.

$ ps aux
root      1234  0.0  0.3 225280  7764 ?        Ss   Jun06   0:15 /sbin/firefox
root         2  0.0  0.0      0     0 ?        S    Jun06   0:00 [kthreadd]
root         3  0.0  0.0      0     0 ?        I<   Jun06   0:00 [rcu_gp]

The above command mentions details of all processes running on our system. If you want to kill only certain processes whose information(PID, username, command, start date, etc.) contain specific keywords, pass the above output to grep command using piping (|).

$ ps aux | grep keyword

For example, 
ps aux | grep firefox
root      1234  0.0  0.3 225280  7764 ?        Ss   Jun06   0:15 /sbin/firefox

The above command will only list processes whose information match your keyword. The second column of grep command’s output contains the PID of each process. So we will use awk command to extract this column for each row, by passing the about command’s output to awk command.

$ ps aux | grep keyword | awk '{print $2}'

Once you have the PIDs of processes that you want to kill, you can pass them to xargs command. In xargs command we will use kill -9 command to terminate the processes.

$ ps aux | grep keyword | awk '{print $2}' | xargs kill -9 

Now xargs will create individual kill commands for each PID and execute them one by one.

kill -9 1234

Alternatively, you can also pass the list of PIDs directly to kill command as shown below.

$ kill -9 $(ps aux | grep KeyWordHere | awk '{print $2}')

In this article, we have learnt how to use Xargs command to kill process.

Also read:

How to Enable Full Disk Encryption in Ubuntu
How to Insert Item into JS Array At Specific Index
How to Find Files Larger Than 100Mb
How to Undo & Redo in Nano Editor
How to Undo & Redo in Vim/Vi Editor

Leave a Reply

Your email address will not be published.