xargs. This guide covers:
- Command substitution with backquotes and
$(...) - Storing outputs in variables
- Processing file lists with
xargs - Handling special characters and custom argument placement
Table of Contents
- Command Substitution
1.1 Using Backquotes
1.2 Using$(...)Syntax
1.3 Assigning Output to a Variable - Processing Input with xargs
2.1 Basic xargs Example
2.2 Limiting Arguments per Invocation
2.3 Handling Filenames with Spaces
2.4 Placing Arguments at a Specific Position - Common xargs Options
- Links and References
Command Substitution
Command substitution allows you to embed the output of one command into another or assign it to a variable. Bash supports two forms:- Backquotes:
`…` - Dollar parentheses:
$(…)
Using Backquotes
date +%Y-%m-%d generates 2022-12-13, which mkdir uses as the directory name.
Backquotes can be harder to nest and read. Consider using
$(...) for complex commands.Using $(...) Syntax
The $(...) form improves readability and nesting:
$(...) produce identical results.
Assigning Output to a Variable
Store command output in a variable for reuse:Processing Input with xargs
xargs builds and executes command lines from standard input. It’s perfect for bulk processing of filenames and other arguments.
Basic xargs Example
Find all files in/usr/share/icons starting with debian and report their dimensions via ImageMagick’s identify:
findlists matching files.- Pipe the list into
xargs. xargsrunsidentifywith-formatto printfilename: width×height.
Limiting Arguments per Invocation
By default,xargs packs as many items as possible per command. Use -n or -L to control batching:
Handling Filenames with Spaces
Filenames containing spaces or special characters require a null separator:- Each match is terminated with
\0. xargs -0reads these safely.dushows disk usage, thensort -norders by size.
Always use
-print0 with find and -0 with xargs when processing arbitrary filenames to avoid word-splitting issues.Placing Arguments at a Specific Position
Use-I with a placeholder (e.g., {} or PATH) to insert items at a custom position:
{} with the filename.
Common xargs Options
| Option | Description | Example |
|---|---|---|
| -n N | Use at most N arguments per command | xargs -n 1 echo |
| -L N | Use at most N lines per command | xargs -L 3 ls -l |
| -0 | Input items are null-terminated (\0) | find . -print0 | xargs -0 rm |
| -I X | Replace placeholder X in the command line | xargs -I {} cp {} /backup/ |
| -P N | Run up to N processes in parallel | xargs -P 4 -n 1 gzip |