Glossary

xargs

xargs reads items from standard input and constructs command lines by appending them to a given command. It is the bridge between commands that produce lists (find, ls, cat file) and commands that take arguments rather than stdin (rm, mv, kill). Without xargs, building such commands by hand or with shell loops is tedious and fragile.

find . -name "*.tmp" | xargs rm              # delete matches
find . -name "*.tmp" -print0 | xargs -0 rm   # handle spaces safely
echo file1 file2 | xargs -n 1 echo           # one per invocation
cat urls.txt | xargs -P 8 -n 1 curl -O       # 8 parallel downloads

The -print0/-0 pairing uses NUL bytes as separators, which is the only safe way to handle filenames containing spaces, newlines, or quotes. The -P N option runs up to N invocations in parallel, making xargs a surprisingly capable lightweight job scheduler for embarrassingly parallel work.

For simple cases, the -exec option of find can replace xargs: find . -name "*.tmp" -exec rm {} +. The + variant batches arguments efficiently, similar to xargs's default behaviour. Both have their place, but xargs remains a standard tool in every shell user's repertoire.

Related terms: Pipe, find, exec

Discussed in:

Also defined in: Textbook of Linux