xargs stands for build and execute, a somewhat odd name (many commands in linux are abbreviated, and all seem odd to me). Another explanation might be easier to remember: execute with arguments.

Use the tldr tool to see the basic usage of xargs.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
$ tldr xargs
xargs
Execute a command with piped arguments coming from another command, a file, etc.The input is treated as a single block of text and split into separate pieces on spaces, tabs, newlines and end-of-file.More information: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/xargs.html.

 - Run a command using the input data as arguments:
   {{arguments_source}} | xargs {{command}}

 - Run multiple chained commands on the input data:
   {{arguments_source}} | xargs sh -c "{{command1}} && {{command2}} | {{command3}}"

 - Delete all files with a .backup extension (-print0 uses a null character to split file names, and -0 uses it as delimiter):
   find . -name {{'*.backup'}} -print0 | xargs -0 rm -v

 - Execute the command once for each input line, replacing any occurrences of the placeholder (here marked as _) with the input line:
   {{arguments_source}} | xargs -I _ {{command}} _ {{optional_extra_arguments}}

 - Parallel runs of up to max-procs processes at a time; the default is 1. If max-procs is 0, xargs will run as many processes as possible at a time:
   {{arguments_source}} | xargs -P {{max-procs}} {{command}}

The purpose of xargs is to redirect the output of one command to the arguments of another command, and then execute that command .

tldr is a tool to see the basic usage of commands in linux, after all man <command> shows too much content to read easily. And tldr <command> will list the basic and common usage of commands, tldr is short for too long don’t read. If you don’t have it installed, you can run: sudo apt install tldr.

To explain what the xargs command does, look at an example: delete all the empty files in the directory.

Create some files.

1
2
$ mkdir tmp
$ touch tmp/file{1..100}.txt

Use find <dir> -empty to see the empty files in the tmp/ directory (all the files you just created are empty).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
$ cd tmp/
$ find . -empty
./file57.txt
./file51.txt
./file78.txt
./file7.txt
./file92.txt
./file19.txt
./file39.txt
./file76.txt
...

You can delete these empty files via pipeline, you may use the rm command directly.

1
2
3
$ find . -empty | rm
rm: missing operand
Try 'rm --help' for more information.

But it doesn’t work because the rm command doesn’t read the standard input, so the rm command fails. The execution of the rm command requires parameters, i.e., the file to be deleted, so how to pass the result of the find command as a parameter to the rm command and execute the command?

This is exactly what the xargs command does.

1
$ find . -empty | xargs rm