Skip to main content
Learn how to capture command output in Bash and build powerful pipelines using 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

  1. Command Substitution
    1.1 Using Backquotes
    1.2 Using $(...) Syntax
    1.3 Assigning Output to a Variable
  2. 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
  3. Common xargs Options
  4. 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

Here, 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:
Both backquotes and $(...) 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:
Output:
Steps:
  1. find lists matching files.
  2. Pipe the list into xargs.
  3. xargs runs identify with -format to print filename: 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:
  1. Each match is terminated with \0.
  2. xargs -0 reads these safely.
  3. du shows disk usage, then sort -n orders 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:
This moves each video file from subdirectories into the current directory, replacing {} with the filename.

Common xargs Options

OptionDescriptionExample
-n NUse at most N arguments per commandxargs -n 1 echo
-L NUse at most N lines per commandxargs -L 3 ls -l
-0Input items are null-terminated (\0)find . -print0 | xargs -0 rm
-I XReplace placeholder X in the command linexargs -I {} cp {} /backup/
-P NRun up to N processes in parallelxargs -P 4 -n 1 gzip

Watch Video