The xargs
command in UNIX is a command line utility for building an execution pipeline from standard input. Whilst tools like grep
can accept standard input as a parameter, many other tools cannot. Using xargs
allows tools like echo
and rm
and mkdir
to accept standard input as arguments.
echo 'one two three' | xargs mkdir ls one two three
The most common usage of xargs
is to use it with the find
command. This uses find
to search for files or directories and then uses xargs
to operate on the results. Typical examples of this are changing the ownership of files or moving files.
find
and xargs
can be used together to operate on files that match certain attributes. In the following example files older than two weeks in the temp folder are found and then piped to the xargs command which runs the rm
command on each file and removes them.
find /tmp -mtime +14 | xargs rm
The find
command supports the -exec
option that allows arbitrary commands to be performed on found files. The following are equivalent.
find ./foo -type f -name "*.txt" -exec rm {} \; find ./foo -type f -name "*.txt" | xargs rm
So which one is faster? Let’s compare a folder with 1000 files in it.
time find . -type f -name "*.txt" -exec rm {} \; 0.35s user 0.11s system 99% cpu 0.467 total time find ./foo -type f -name "*.txt" | xargs rm 0.00s user 0.01s system 75% cpu 0.016 total
Clearly using xargs is far more efficient. In fact several benchmarks suggest using xargs
over exec {}
is six times more efficient.
The -t
option prints each command that will be executed to the terminal. This can be helpful when debugging scripts.
echo 'one two three' | xargs -t rm rm one two three
The -p
command will print the command to be executed and prompt the user to run it. This can be useful for destructive operations where you really want to be sure on the command to be run.
echo 'one two three' | xargs -p touch touch one two three ?...
It is possible to run multiple commands with xargs
by using the -I
flag. This replaces occurrences of the argument with the argument passed to xargs. The following echos a string and creates a folder.
cat foo.txt one two three cat foo.txt | xargs -I % sh -c 'echo %; mkdir %' one two three ls one two three
This article is contributed by Neha. If you like dEexams.com and would like to contribute, you can write your article here or mail your article to admin@deexams.com . See your article appearing on the dEexams.com main page and help others to learn.