Getting started
Introduction
xargs turns standard input into command arguments. It batches long lists, handles awkward filenames with NUL-delimited input, and runs jobs in parallel.
- xargs(1) manual (man7.org)
- POSIX xargs (pubs.opengroup.org)
Standard input
$ printf 'a b\nc\n' | xargs echo
a b c
xargs splits items on whitespace and appends them to echo (the default command), batching as many as fit on one command line.
See: xargs(1)
Items per command
$ printf 'a b c d e\n' | xargs -n 2 echo
a b
c d
e
-n caps the arguments per invocation; the last batch may be shorter.
See: -n/--max-args in xargs(1)
Verbose execution
$ printf 'a b\n' | xargs -t -n 1 echo 2>&1
echo a
a
echo b
b
-t prints each command to stderr before running it.
See: -t/--verbose in xargs(1)
Empty input
GNU default
$ printf '' | xargs echo | wc -l
1
With -r
$ printf '' | xargs -r echo | wc -l
0
GNU xargs runs the command once with no arguments; -r skips it.
See: POSIX xargs
NUL-delimited input
NUL input from find
$ find . -name '*.txt' -print0 \
| xargs -0 -n 1 echo
./my file.txt
./notes.txt
-0 reads NUL-terminated items, so spaces and newlines stay in one argument.
See: xargs(1), -0
NUL-delimited strings
$ printf 'a b\0c d\0' | xargs -0 -n 1 echo
a b
c d
Pair -0 with a producer that emits \0-terminated records.
See: xargs(1), --null
Other delimiters
$ printf 'a,b,c' | xargs -d, -n 1 echo
a
b
c
-d sets a single-character delimiter; it is a GNU extension.
See: xargs(1), -d
Replacing arguments
Placeholder
$ printf 'one\ntwo words\n' | xargs -I {} echo 'item: {}'
item: one
item: two words
-I replaces each {} and runs the command once per item.
See: -I/--replace in xargs(1)
Placeholder with NUL input
$ find . -name '*.txt' -print0 | xargs -0 -I {} echo 'file: {}'
file: ./my file.txt
file: ./notes.txt
-I implies one item per command, so keep -0 when names may contain spaces.
See: POSIX xargs
Parallel jobs
Fixed worker count
$ find . -name '*.txt' -print0 | xargs -0 -P 4 -n 1 wc -l
1 ./my file.txt
2 ./notes.txt
-P runs up to four commands at once; output order follows completion.
See: -P/--max-procs in xargs(1)
One item per job
$ printf 'a\nb\n' | xargs -P 2 -I {} \
sh -c 'echo "start {}"; sleep 0.1; echo "end {}"'
start a
start b
end b
end a
Combine -P with -I for one independent job per item.
See: xargs(1), -P
0 Comments for this cheatsheet. Write yours!