What does `xargs` do, and which flags matter?
IntermediateConceptfind, xargs, jq and yq
Answer
xargs reads items from stdin and runs a command with them as arguments, batching to stay under the argument limit.
| Flag | Purpose |
|---|---|
-0 |
items are NUL-separated (pair with find -print0, grep -Z) |
-n N |
at most N items per command |
-I {} |
replace {} with each item (implies one item per command) |
-P N |
run up to N commands in parallel |
-r |
GNU: do not run the command if input is empty |
-t |
print each command before running it |
find . -name '*.png' -print0 | xargs -0 -P 4 -n 20 optipng -quiet
kubectl get ns -o name | xargs -r -n1 -I{} kubectl get pods -n {} --no-headers
Without -0, xargs splits on whitespace and treats quotes specially, so filenames with spaces or apostrophes break.
More on find, xargs, jq and yq
What are the most useful `find` predicates for operations work?BeginnerWhat is the difference between `-exec cmd {} \;`, `-exec cmd {} +` and `-delete`?IntermediateHow does `find` evaluate `-o` (OR) and why do you need parentheses?AdvancedWhy is `find | xargs rm` dangerous and what is the safe form?IntermediateWhat is `jq` and what are the filters you use every day?BeginnerHow do you pass shell variables into `jq` safely?Intermediate