The xargs command
The xargs command turns lines of text into arguments for another command: find .
The xargs command turns lines of text into arguments for another command: find . -name "*.tmp" | xargs rm deletes every file find lists.
Taught in Advanced, lesson 37
A practice shell in your browser that behaves like bash on Linux for these commands. Nothing you type leaves the page.
Usage
xargs [OPTION]... [COMMAND [ARG]...]
Run a command with words from its input as arguments. Reads words from a pipe and adds them to the end of a command, then runs it. Many commands take file names as arguments rather than from a pipe, so xargs joins them: find . -name "*.tmp" | xargs rm deletes every file find lists. Blanks separate the words (quote a name that has spaces in it). With no command, xargs runs echo.
How to use xargs
Run a command on a list of files
Many commands take file names as arguments, not from a pipe. xargs joins the two.
ls *.txt | xargs wc -l1 diary.txt 1 draft.txt 6 fruit.txt 7 names.txt 14 notes.txt 1 old.txt 1 part1.txt 1 part2.txt 2 report.txt 6 scores.txt 1 shared.txt 5 shopping-new.txt 4 shopping.txt 50 total
Delete what find finds
find . -name "*.tmp" | xargs rm -vremoved './a.tmp' removed './b.tmp'
A few at a time: xargs -n
cat names.txt | xargs -n 3Leo Ava Mia Ava Leo Ava Zac
Put each item in a command: xargs -I
-I {} runs the command once per line, with {} replaced by the line.
ls *.jpg | xargs -I {} cp {} photos/{}.bak && ls photosbeach.jpg.bak cat.jpg.bak
See the commands it runs: xargs -t
-t prints each command (to the error output) before running it.
echo a.tmp b.tmp | xargs -t rmrm a.tmp b.tmp
Options
| -n N, --max-args=N | use at most N words for each run of the command |
|---|---|
| -I TEXT | run the command once per line, with TEXT in it replaced by the line (often -I {}) |
| -t, --verbose | print each command before running it |
| -r, --no-run-if-empty | don’t run the command at all when there is no input |
| -0, --null | words are separated by a NUL character (for find -print0) |
| -L N | use N lines for each run of the command |
More examples
find . -name "*.tmp" | xargs rmcat names.txt | xargs -n 2Leo Ava Mia Ava Leo Ava Zac
sort -u fruit.txt | xargs -I {} echo "I like {}"I like apple I like fig I like pear
ls *.jpg | xargs -I {} cp {} photos/Questions about xargs
What is the difference between a pipe and xargs?
A pipe sends text to a command’s input. xargs reads that text and puts it on the command line as arguments, which is what commands like rm, cp and mkdir need.
What about file names with spaces?
xargs splits on blanks, so a name with a space becomes two words. Use find -print0 | xargs -0, which separates names with a NUL character instead.
Learn it step by step
Related commands
Every everyday command on one page, to print or keep open: the Linux commands cheat sheet.