Home [Linux] xargs command and usage example
Post
Cancel

[Linux] xargs command and usage example

Why use the xargs command?

I wanted to utilize the output from certain commands to perform new commands in bulk. The xargs command has the ability to read a data stream and generate and execute a command line. This means that you can take the output of a specific command and use it as an argument to a new command.

Usage example

Delete all files with a specific file extension

If you want to delete all files with the .sh extension, you can do it with the xargs command as shown below. Of course, you can give the rm command a pattern to do the same thing, but I’ve used it here to show that it can be used in combination with other commands.

1
$ ls | grep "\.sh$" | xargs rm

The above command works by looking for .sh extensions in the ls output and entering them after rm in xargs.

Utilize the output of a specific command to create a new command

If you want to create a new command that truncates the output of a specific piece of text, you can do so via xargs.

1
2
3
4
$ cat test.txt
1 kevin
2 william
3 mickey

Let’s say you have the same information in your test.txt, but you want to get only the name information after the number and execute the command below.

1
$ deleteuser -u USERNAME -f

In this case, the command can be executed via xargs as shown below.

1
cat test.sh | awk '{ print $2 }' | xargs -I{} deleteuser -u {} -f

Here, xargs used the -I option. This option tells us to put the result of the previous command in {} in the previous command. So deleteuser -u {} with the username.

After executing the above command

1
2
3
deleteuser -u kevin -f
deleteuser -u william -f
deleteuser -u mickey -f

in sequence, with the same effect.

This post is licensed under CC BY 4.0 by the author.