xargs: turn lines of input into command arguments
xargs turns its input into command arguments, but by its own quoting and blank rules, not one argument per line.
Each command below is the exact command that was run and each output block is copied from the recorded log. Test ids, log hashes and exit statuses are in the evidence table.
TE-20-A: xargs splits on whitespace, so a name with a space breaks; -0 with -print0 survives
Setup for this run, inside a throwaway directory (mktemp -d):
printf 'x\n' > 'a b.txt'Command:
printf '%s\n' 'a b.txt' | xargs -n1 printf '[%s]\n'; echo '--'; find . -maxdepth 1 -name 'a b.txt' -print0 | xargs -0 -n1 printf '[%s]\n'Recorded output:
[a]
[b.txt]
--
[./a b.txt]TE-20-B: xargs -n2 passes two arguments to each run of the command
No setup needed: the command below creates what it uses in the throwaway folder.
Command:
printf '1 2 3 4\n' | xargs -n2 echoRecorded output:
1 2
3 4Exit status: 0. This status and the output match what was written before the run. This is the status of xargs, the last command in the pipe.
TE-20-C: expected non-zero exit: xargs exits with status 123 when the command it runs exits with status 1
No setup needed: the command below creates what it uses in the throwaway folder.
Command:
printf 'x\n' | xargs falseRecorded output: none, standard output was empty.
Exit status: 123. This status and the output match what was written before the run. This is the status of xargs, the last command in the pipe.
TE-20-B: the input 1 2 3 4 was passed two at a time, so echo printed 1 2 and then 3 4. TE-20-C: xargs false exited with status 123 and printed nothing.
Limits
Names with spaces, newlines or quotes break; use -print0 with -0 or -exec.
Source
Evidence
TE-20-A: xargs splits on whitespace, so a name with a space breaks; -0 with -print0 survives
- logs: one recorded log for each row above
- Recorded on: Linux x86_64, kernel 7.3.4; bash 5.1.16; git 2.34.1; python 3.10.12; findutils 4.8.0; grep 3.7; sed 4.8; gawk 5.1.0; tar 1.34; curl 7.81.0. Locale C.UTF-8, TZ=UTC.
Evidence table
| Test | What it checks | Exit | Verdict | Log sha256 (first 12) | |---|---|---|---|---| | TE-20-A | xargs splits on whitespace, so a name with a space breaks; -0 with -print0 survives | 0 | PASS | 1d62678ce4bb | | TE-20-B | xargs -n2 passes two arguments to each run of the command | 0 | PASS | 091e2fe699f3 | | TE-20-C | expected non-zero exit: xargs exits with status 123 when the command it runs exits with status 1 | 123 | PASS | 59daad143467 |
Every row has a recorded log holding the setup commands, the command, stdout, stderr, exit status and the final directory state. The first 12 characters of the log's sha256 are in the table.
All full guides: All guides