xargs: Build Commands
Many commands take their work as arguments (rm file1 file2), not as input through a pipe. xargs bridges the gap: it reads items from its input and appends them as arguments to a command. With it, the output of find, grep -l or any list becomes something you can act on.
The basic idea
printf 'notes.txt\ntodo.txt\nideas.txt\n' > files.lst
xargs touch < files.lst
ls
echo "---"
printf 'one\ntwo\nthree\n' | xargs echo "items:"files.lst
ideas.txt
notes.txt
todo.txt
---
items: one two three
xargs touch turned three input lines into one command: touch notes.txt todo.txt ideas.txt. Without a command, xargs runs echo.
Controlling how many arguments per command
-n N passes at most N items per command call. -I {} runs the command once per item and puts the item wherever {} appears:
printf '%s\n' a b c d e | xargs -n 2 echo "batch:"
echo "---"
printf '%s\n' report invoice receipt | xargs -I {} echo "creating {}.pdf from {}.md"batch: a b
batch: c d
batch: e
---
creating report.pdf from report.md
creating invoice.pdf from invoice.md
creating receipt.pdf from receipt.md
Working with find
The most common pairing is find ... | xargs .... File names may contain spaces, so the safe form uses null characters as separators: find -print0 with xargs -0:
mkdir -p docs
touch "docs/annual report.txt" docs/summary.txt docs/old.bak "docs/draft copy.bak"
find docs -name '*.bak' | xargs rm 2>&1 | sort
echo "--- the unsafe version broke on spaces. Safe version:"
find docs -name '*.bak' -print0 | xargs -0 rm -v | sort
echo "--- left:"
ls docsrm: cannot remove 'copy.bak': No such file or directory
rm: cannot remove 'docs/draft': No such file or directory
--- the unsafe version broke on spaces. Safe version:
removed 'docs/draft copy.bak'
--- left:
annual report.txt
summary.txt
The first attempt split draft copy.bak into two names, docs/draft and copy.bak, which don't exist (docs/old.bak has no space, so that one was removed). -print0/-0 separates names with the null byte, the one character a file name can't contain.
Tip:
find ... -exec cmd {} +does the same job asfind -print0 | xargs -0 cmdand is often simpler.xargsshines when the list comes from somewhere other thanfind.
Showing and confirming commands
-t prints each command before running it (great for learning and debugging); -p asks for confirmation (interactive, so only for terminals):
printf 'logs\ncache\ntmp\n' | xargs -t mkdir -p 2>&1
lsmkdir -p logs cache tmp
cache
logs
tmp
-t writes to standard error, which is why it's redirected into the output here with 2>&1.
Running in parallel
-P N runs up to N commands at the same time, which speeds up slow jobs like compressing files or downloading URLs. The output order of parallel jobs isn't fixed, so collect and sort it:
for i in 1 2 3 4; do seq 1 1000 > "data$i.txt"; done
ls data*.txt | xargs -P 4 -n 1 gzip
ls data*.gz | sortdata1.txt.gz
data2.txt.gz
data3.txt.gz
data4.txt.gz
Combining with grep
mkdir -p src
printf 'import os\nprint(os.getcwd())\n' > src/a.py
printf 'print("no imports")\n' > src/b.py
printf 'import os, sys\n' > src/c.py
grep -l 'import os' src/*.py | xargs wc -l
echo "---"
grep -l 'import os' src/*.py | xargs sed -i 's/import os/import pathlib/'
grep -h import src/*.py 2 src/a.py
1 src/c.py
3 total
---
import pathlib
print("no imports")
import pathlib, sys
grep -l lists matching files and xargs hands them to the next command: first a line count, then an in-place edit of exactly those files.
Empty input
When the input is empty, GNU xargs still runs the command once, with no arguments. For rm that's an error; for a command like wc -l it would even wait for keyboard input. Add -r (--no-run-if-empty) to skip the run instead:
: | xargs rm
echo "status: $?"
: | xargs -r rm
echo "with -r status: $?"rm: missing operand
Try 'rm --help' for more information.
status: 123
with -r status: 0
Exit status 123 means "at least one command run by xargs failed".
Test yourself
What does echo 'a b c' | xargs -n 1 echo print?
a b con one line- a, b and c on three lines
- Nothing
- An error
Why use find -print0 | xargs -0?
- It's faster
- It handles file names containing spaces or newlines
- It prints null values
- It's required by find
Which option runs the command once per input item and substitutes it at {}?
- -n {}
- -I {}
- -0
- -P {}