find gives you a list of files, but rm, chmod or mv do not read that list: they expect names on their command line. xargs reads the list on its standard input, splits it into arguments and runs the command with those arguments. The trap is the splitting: by default, a space cuts, and a file name like mon fichier.txt becomes two arguments, with no error message.
The page Advanced redirections, here-doc and xargs presents xargs among the shell tools: the ARG_MAX limit, -0, -r, -I, -n1, -P and lists written inside a script. Here, xargs is covered on its own: how it splits, how it groups, how to preview it and have it delete files on a copy. Searching for files is covered in find, and advanced parallelism in GNU Parallel.
What you will learn
- Turn a list, read from a file or from a pipe, into arguments for a command
- Choose the splitting: spaces by default, line end with
-d, null byte with-0 - Group arguments with
-nand place the argument where you want with-I - Preview with
echo,-tand-p, and avoid the empty call with-r - Read the exit code of
xargsand run calls in parallel with-P - Delete files on a copy after checking the list
Prerequisites
You know how to open a Linux terminal, create a folder and move into it with cd, copy (cp), move (mv) and delete (rm) files. wc -l counts the lines of an output. Two notions are used further on: redirections and pipes (|, <), and find to produce the list of files.
Create the practice folder
All the examples run in ~/xargs-lab. The commands below create liste.txt (the list of the map), a piege folder and its list a-supprimer.txt (for the first exercise), a tmp folder for the full case and a logs folder for the second exercise. Several names contain a space, on purpose. The file names use French words, which the commands keep: liste is "list", piege "trap", a-supprimer "to delete", rapport final "final report", mon fichier "my file", vieux "old", anciens "old ones", copie "copy".
mkdir ~/xargs-lab && cd ~/xargs-lab && {printf '%s\n' 'a.txt' 'mon fichier.txt' 'b.txt' > liste.txtprintf '%s\n' 'rapport final.txt' > a-supprimer.txtmkdir piege tmp logstouch piege/rapport piege/final.txt 'piege/rapport final.txt' piege/notes.txttouch tmp/x1.tmp "tmp/x 2.tmp" tmp/x3.tmptouch logs/app.log "logs/vieux 1.log" "logs/vieux 2.log" "logs/vieux 3.log" logs/notes.txt}The braces group the commands behind the &&: they only run if mkdir ~/xargs-lab succeeds. If the folder already exists, nothing else is written: delete the old one (section "Clean up the practice folder"). The names in liste.txt match no file: echo does not need them to exist.
The outputs come from GNU findutils 4.9.0 (Ubuntu 24.04); xargs --version | head -1 prints your version. The order of the lines of a find depends on the file system: compare lists without taking the order into account.
The xargs command in detail
An xargs command is written in this order: the options that set the splitting and the grouping, then the command to run and its fixed arguments. The list arrives on standard input, from a file with < or through a pipe. Without a command, xargs runs echo. Read the line from left to right: each number points to the explanation of that piece.
Anatomy of the command
Syntaxxargs [options] command [fixed arguments]
xargs-d '\n'-n 1echofichier:< liste.txt -
xargsthe programIt reads a list on its standard input. -
-d '\n'the splittingoptionalWhat separates two arguments. Without-dor-0: spaces, tabs and line ends. -
-n 1the groupingoptionalThe number of arguments per call. Without-n: as many as possible. -
echothe commandoptionalThe onexargsruns. With no command, it isecho. -
fichier:a fixed argumentoptionalPassed to each call, before the arguments of the list. -
< liste.txtthe listA file, or more often the output of a pipe.
Outputfichier: a.txt, then one line per file
How xargs builds commands, step by step
xargs reads the list, splits it into arguments, then runs the command as many times as the grouping requires. The map follows liste.txt, three lines including mon fichier.txt, with echo as the command.
Before you turn the map options on, predict the result for xargs echo < liste.txt: how many echo commands are run, and with which arguments? Ask the same question with -d '\n', with -n 1, then with both. Then check on the map: look at the "Pending arguments" area and the output of the commands that were run.
Mental model
How xargs builds commands
read the listsplit it into argumentsrun the command as many times as the grouping asks for
Try Input · liste.txt
Split, group, run
Arguments waiting
$ xargs echo < liste.txt
- xargs reads “a.txt”: one more argument.
- xargs reads “mon fichier.txt” and splits at the space: two arguments, “mon” and “fichier.txt”. The file name is lost, with no message.
- xargs reads “b.txt”: one more argument.
- The list is over: xargs runs echo only once, with every argument. The output looks right, the splitting does not show.
- A single command run for 3 files.
What the animation shows
- xargs makes arguments, for a command that does not read its standard input, such as
rmorchmod. - By default, a space splits. A name with a space becomes two arguments, with no message.
- By default, a single call receives the whole of a short list.
-n 1runs the command once per argument. - The splitting does not show with `echo`: add
-n 1to check it.
Golden rules
Pass names separated by a null byte
It is the only separator a path cannot contain:
find . -name '*.log' -print0 | xargs -0 ls -lLook before acting
Put echo in front of the command, read the lines, then remove it:
find . -name '*.tmp' -print0 | xargs -0 -n 1 echo rmEssential vocabulary
Split · what separates two arguments
-d '\n'- Split at line ends
xargs -d '\n' -n 1 echo < liste.txt→ 3 lines, one per file -0- Split at null bytes
printf 'a\0b c\0' | xargs -0 -n 1 echo→ a, then b c -I {}- One line per call, placed where you want
xargs -I {} echo '[{}]' < liste.txt→ 3 lines between brackets -r- Run nothing if the list is empty
xargs -r echo < /dev/null→ nothing
Group and run · how many calls, with what
-n 1- One argument per call
xargs -n 1 echo < liste.txt→ 4 lines: the name is split -P 2- Two calls at the same time
xargs -n 1 -P 2 echo < liste.txt→ 4 lines, order varies xargs echo- Without -r, an empty list runs the command with nothing
xargs echo < /dev/null→ an empty line $?- Code 123 when a call fails
xargs -n 1 false < liste.txt; echo $?→ 123
Pass a list to a command
xargs echo < liste.txt reads the file on its standard input and runs echo a single time, with all the arguments. xargs -a liste.txt echo does the same thing by naming the file. In a pipeline, the source is the output of the command on the left: find ... | xargs ....
xargs echo < liste.txta.txt mon fichier.txt b.txtA single line: the splitting cannot be seen here. Going through xargs is necessary for rm, chmod or mv, which do not read their standard input: find . -name '*.tmp' | rm fails with rm: missing operand.
Split the list: spaces, line ends, null byte
By default, xargs cuts the input at spaces, tabs and line ends. To see the cut, run the command once per argument: that is the effect of -n 1.
xargs -n 1 echo < liste.txta.txtmonfichier.txtb.txtFour lines for three files: mon fichier.txt became mon and fichier.txt. With rm, it is mon and fichier.txt that would be deleted, if they exist, with no message at all. -d '\n' makes the line end the only separator, which suits a list read from a file.
xargs -d '\n' -n 1 echo < liste.txta.txtmon fichier.txtb.txtFor a list produced by find, the null byte is safer: it is the only byte a path cannot contain. find -print0 ends each path with a null byte, and xargs -0 cuts on it. With printf, you write that byte yourself (\0):
printf 'a\0b c\0' | xargs -0 -n 1 echoab cWith find, the pattern to write by default as soon as files are involved is find ... -print0 | xargs -0 .... In logs, three names contain a space:
find logs -name '*.log' -print0 | xargs -0 ls -1find logs -name '*.log' | xargs ls -1logs/app.log'logs/vieux 1.log''logs/vieux 2.log''logs/vieux 3.log'ls: cannot access 'logs/vieux': No such file or directoryls: cannot access '3.log': No such file or directoryls: cannot access 'logs/vieux': No such file or directoryls: cannot access '2.log': No such file or directoryls: cannot access 'logs/vieux': No such file or directoryls: cannot access '1.log': No such file or directorylogs/app.logThe apostrophes in the first output are added by ls in a terminal around names that contain a space. Without -0, ls looks for six files that do not exist. By default, xargs also interprets quotes and the backslash: an apostrophe in a name gives xargs: unmatched single quote; by default quotes are special to xargs unless you use the -0 option. -0 and -d turn this interpretation off.
The two wrong files deleted
The piege folder contains four files: rapport, final.txt, rapport final.txt and notes.txt. a-supprimer.txt names only one, rapport final.txt. A colleague suggests xargs rm < ../a-supprimer.txt, run from a copy of the folder. Try it, look at what disappeared, then delete the right file.
Try the colleague's command
Copy piege to piege-copie, move into the copy and run the command. Print its exit code with echo $?, then the list of remaining files.
Start again on a fresh copy
Go back to ~/xargs-lab, delete the copy and make it again. Fix the command so that it only deletes the file named in the list.
- xargs -d
- cp -r
A hint 1 / 1
The list contains one line, but rm received two arguments. Choose the separator that keeps the whole line.
I have tried: show the solution
cp -r piege piege-copie && cd piege-copiexargs rm < ../a-supprimer.txt; echo $?ls -1cd .. && rm -r piege-copiecp -r piege piege-copie && cd piege-copiexargs -d '\n' rm < ../a-supprimer.txtls -1cd ..0notes.txt'rapport final.txt'final.txtnotes.txtrapportrapport final.txt gave two arguments, rapport and final.txt. Both existed: rm deleted them, with no message and exit code 0, and the targeted file stayed. With -d '\n', the line forms a single argument.
Group arguments with -n
Without -n, xargs puts as many arguments as possible in each call, within the size limit of a command line. -n N imposes at most N arguments per call.
echo "1 2 3 4 5 6" | xargs -n 2 echo1 23 45 6Three lines: echo was run three times, with two arguments each time. Running one command per file costs one more process per file; keep the default grouping when the command accepts several arguments, like rm or grep.
Place the argument with -I
By default, xargs adds the arguments at the end of the command: echo file.txt | xargs cp /backup/ runs cp /backup/ file.txt, with source and destination reversed. -I {} names a marker that each input line replaces, wherever it is written.
xargs -I {} echo '[{}]' < liste.txt[a.txt][mon fichier.txt][b.txt]Three calls, one per line, and mon fichier.txt stays whole: -I cuts at line ends, not at spaces. Quotes, however, are still interpreted. For files, add -0: find ... -print0 | xargs -0 -I {} ... runs one call per path, whatever its name.
The marker can appear several times, as in cp {} {}.bak. -n and -I cannot be combined: GNU xargs warns that the two options are mutually exclusive and ignores the first of the two.
Never put {} inside a sh -c: with xargs -I {} sh -c 'echo {}', a line a;date runs date. Pass the value as an argument: xargs -I {} sh -c 'echo "$1"' _ {}. The shell receives _ in $0 (its name, unimportant here) and the value in $1, which it handles as text.
Preview before acting: echo, -t and -p
xargs often feeds rm, mv or chmod, which have no way back. Put echo in front of the command: xargs prints the line it would have run, without running anything. With -n 1, you read one command per file.
find tmp -name '*.tmp' -print0 | xargs -0 -n 1 echo rmrm tmp/x1.tmprm tmp/x3.tmprm tmp/x 2.tmpYou must read three rm lines, one per file. One line more signals a splitting you did not expect: fix it before removing echo.
Two options complete this. -t writes each command on standard error just before running it: it is for keeping a trace, not for protecting yourself. -p prints the command and waits for y or n before running it; the answer is read from the terminal, hence the failed to open /dev/tty error in a non-interactive script or a scheduled task.
Empty list and exit code
If the list is empty, GNU xargs runs the command anyway once, with no argument. -r (--no-run-if-empty) removes that empty call.
xargs echo < /dev/null | wc -lxargs -r echo < /dev/null | wc -l10The first command prints an empty line: echo was run without an argument. The second runs nothing. With rm, the empty call gives missing operand; with a command that acts on the current folder when given no target, like du -sh, it measures the current folder. Make a habit of writing -r in scripts, where an empty list is a normal case.
The exit code of xargs tells whether the calls succeeded. It is 123 when at least one call failed. false is a command that always fails, and $? holds the last exit code:
xargs -n 1 false < liste.txt; echo $?123The four calls to false fail (one per argument, as in the splitting example), and xargs does not tell them apart: 123 means at least one call failed, not "how many". 126 and 127 mean that xargs could not run the command: it is not executable, or it cannot be found. 124 signals that a call returned 255, which stops xargs without processing the rest.
Run calls in parallel with -P
-P N runs up to N calls at the same time. To see it, you need a command that takes time: sleep 1 waits one second. printf '1\n1\n' writes two lines 1, so xargs -n 1 sleep runs sleep 1 twice. time gives the duration of what is between parentheses: read the real line.
time (printf '1\n1\n' | xargs -n 1 sleep)time (printf '1\n1\n' | xargs -n 1 -P 2 sleep)Without -P, the two pauses follow each other. With -P 2, they run together: the real duration goes from 2 seconds to 1. -P spreads calls: without -n or -I, a short list fits in a single call, and a single process runs. The gain exists when each call only occupies one core or waits for the network; start from the number of cores given by nproc.
The order of the outputs is no longer guaranteed, and those of two calls can interleave. If the result must stay readable, have each call write to its own file.
Full case: delete on a copy
tmp contains three .tmp files, including x 2.tmp. You work on tmp-copie, never on the original.
test ! -e tmp-copie && cp -r tmp tmp-copiefind tmp-copie -name '*.tmp' -print0 | xargs -0 -n 1 echo rmfind tmp-copie -name '*.tmp' -print0 | xargs -0 -r rmfind tmp-copie -type f | wc -lfind tmp -type f | wc -lrm tmp-copie/x1.tmprm tmp-copie/x3.tmprm tmp-copie/x 2.tmp03test ! -e refuses the copy if tmp-copie already exists: cp -r would otherwise copy the folder inside it. The first three commands copy, preview three rm then run them. The two wc -l compare: tmp-copie must hold 0 files and tmp still 3. To start again: rm -r tmp-copie, then the same commands.
Move the old logs of a copy
The logs folder contains app.log, notes.txt and three files named vieux, a space, a digit and .log. In a copy of logs, add a fourth old log whose name contains an apostrophe, then move all four into an anciens subfolder, without touching logs. mv expects the destination last: the arguments that xargs adds at the end do not fit.
Copy the folder
Create logs-copie, a copy of logs, the logs-copie/anciens folder and the empty file logs-copie/vieux d'avril.log.
Preview the moves
Search for the files to move in logs-copie, without going down into anciens (the files already moved would be found there), and print the mv commands without running them.
Move and count
Run the moves, then count the files in anciens, those left in logs-copie, and those in logs.
- find -print0
- xargs -0
- xargs -I
A hint 1 / 2
The names contain a space, and one of them an apostrophe: choose the separator a path cannot contain, on both sides of the pipe.
A hint 2 / 2
An xargs option places the argument wherever you choose in the command. A find option limits the depth.
I have tried: show the solution
test ! -e logs-copie && cp -r logs logs-copiemkdir logs-copie/anciens; touch "logs-copie/vieux d'avril.log"find logs-copie -maxdepth 1 -type f -name 'vieux*' -print0 | xargs -0 -I {} echo mv {} logs-copie/anciens/find logs-copie -maxdepth 1 -type f -name 'vieux*' -print0 | xargs -0 -I {} mv {} logs-copie/anciens/find logs-copie/anciens -type f | wc -lfind logs-copie -maxdepth 1 -type f | wc -lfind logs -type f | wc -lmv logs-copie/vieux d'avril.log logs-copie/anciens/mv logs-copie/vieux 3.log logs-copie/anciens/mv logs-copie/vieux 2.log logs-copie/anciens/mv logs-copie/vieux 1.log logs-copie/anciens/425-I {} places each name before the destination and runs one mv per file. Without -print0 and -0, -I would keep the spaces, but the apostrophe would stop xargs with unmatched single quote and exit code 1. logs keeps its five files.
Which command should I choose?
find can run a command itself on the files it finds, and other tools cover the cases that xargs does not handle well. Start from the need.
| Need | Command |
|---|---|
Group the paths like xargs, names with spaces handled | find ... -exec COMMAND {} + |
| Use a pipe or a redirection for each item | xargs -I {} sh -c '... "$1" ...' _ {} |
| Archive a long list of files | tar --null --files-from=- |
| Advanced parallelism, remote machines | GNU Parallel |
List written in a script, -I, -P | Advanced redirections |
-exec COMMAND {} + groups the paths like xargs and passes names with spaces without -print0. xargs keeps the advantage when the list does not come from find, or when you need -P. With tar, xargs reruns tar for each group when the list exceeds the size of a command line, and each rerun overwrites the archive: tar --null --files-from=- reads the whole list without splitting it.
Troubleshooting
When xargs misbehaves, check the splitting first: put echo back in front of the command and add -n 1 to read what xargs built.
| Symptom | Cause | Solution |
|---|---|---|
No such file or directory on pieces of a name | Name cut at the space | -print0 and -0, or -d '\n' |
unmatched single quote | Apostrophe in a name | -0 or -d '\n' |
{} appears as is in the command | -I {} forgotten | Add -I {} before the command |
... | xargs -I {} echo {} | wc -c gives a single total | The second pipe applies to the overall output of xargs, not to each item | Wrap it: xargs -I {} sh -c 'echo "$1" | wc -c' _ {} |
For Argument list too long, the cause is the shell and not xargs: rm /var/log/app/*.log expands the pattern into a single line that the kernel refuses. find ... -print0 | xargs -0 rm fixes the problem, because xargs splits the list into groups that respect the limit. xargs --show-limits < /dev/null prints the limits applied on your machine.
Clean up the practice folder
When you are done, delete the practice folder. First run the list with -print: it must only show paths under ~/xargs-lab.
find ~/xargs-lab -printrm -r ~/xargs-labThe folder disappears with the copies tmp-copie and logs-copie. This command touches nothing else.
Key points
xargsreads a list on its standard input and passes it as arguments to a command; without a command, it runsecho.- By default, a space cuts:
mon fichier.txtbecomes two arguments, with no message.-d '\n'cuts at line ends,find -print0 | xargs -0at the null byte, and that is the pattern to write for files. - Without
-n, a short list goes in a single call;-n 1runs the command once per argument.-I {}places the argument where you want, one call per line, or per path with-0. - Put
echoin front of the command to read what would be run, and add-rso that an empty list runs nothing. - Exit code 123 signals that at least one call failed.
-P Nonly parallelizes if there are several groups, and does not guarantee the order of the outputs. - To delete, preview with
echo, act on a copy, then compare the original and the copy.
Knowledge check
Check that the essentials of this guide are acquired. The questions only cover what has just been explained here.
Knowledge check
Check what you have learned with this interactive quiz
How it works
- The timer starts when you click Start
- Multiple choice, true/false and short answer questions
- You can move between questions
- Detailed results are shown at the end
Starts the quiz and the timer
Review
(0/0)Result saved on this device. It will be sent to your account at the next sync. Sync now
Score by domain
A domain groups several guides and gets several questions, so its score is more reliable than a per-topic score, which often rests on a single question.
Summary
Strengths
No topic passed at 80% on at least two questions yet.
Weak areas
No topic below the pass mark.
Recommended next
Hints before you try again?
Continue the course: GNU Parallel: run commands in parallel
A new full quiz with random questions
Work again only on the questions you missed
FAQ: frequently asked questions
find, find ... -exec COMMAND {} + is enough: it groups the paths and keeps names with spaces.xargs is for lists that come from a file or from another command, or when you want to run calls in parallel with -P.find, separate the paths with a null byte, which a path cannot contain:find . -name '*.log' -print0 | xargs -0 ls -1
For a list written in a file, one name per line, use xargs -d '\n'. Without one of the two, mon fichier.txt becomes two arguments.*.log into a single line, longer than what the kernel accepts. find ... -print0 | xargs -0 COMMAND runs the command several times, with groups that fit under the limit.xargs --show-limits < /dev/null prints the limits of your machine.-P spreads calls across processes. Without -n or -I, a short list fits in a single call, so only one process runs. Add -n 1:printf '1\n1\n' | xargs -n 1 -P 2 sleep
The two one-second pauses run together: the command takes one second instead of two.