KKAIROS
Practical guideIllustrative3 min read

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.

Published:

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 echo

Recorded output:

1 2
3 4

Exit 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 false

Recorded 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.

Ad

Source

Evidence

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