Skip to content

xargs Command Cheat Sheet

xargs reads items from standard input (stdin), delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command one or more times with any initial-arguments followed by items read from standard input.


Synopsis

xargs [options] [command [initial-arguments]]

Basic Usage

Delete all .tmp files found by find.

find /tmp -name "*.tmp" | xargs rm

Handling Filenames with Spaces (-0)

CRITICAL: By default, xargs breaks on spaces. If a file is named My Resume.txt, xargs tries to remove My and Resume.txt. Use -print0 with find and -0 with xargs to handle this safely using null terminators.

find . -name "*.txt" -print0 | xargs -0 rm

Execution Control

Prompt Before Running (-p)

Ask user confirmation for every command.

find . -name "*.log" | xargs -p rm

Max Arguments (-n)

Run the command once for EACH file (instead of passing them all at once).

# Echo each file on a new line
ls | xargs -n 1 echo "Processing:"

Parallel Execution (-P)

Run commands in parallel. This is a powerful feature for speeding up tasks.

# Convert all JPGs to PNGs using 4 cores in parallel
ls *.jpg | xargs -n 1 -P 4 convert -resize 50%
  • -n 1: Pass 1 file at a time to the command.
  • -P 4: Run up to 4 processes simultaneously.
  • -P 0: Run as many as possible (unlimited).

Replacement Strings (-I)

Use a placeholder (like {}) to insert the argument in the middle of a command.

# Move files to 'backup/' folder
ls *.txt | xargs -I {} mv {} backup/
In this mode, {} is replaced by the input line. (Implies -L 1).


Dry Run / Interactive Debugging

See what xargs would execute without running it. Note: xargs doesn't have a --dry-run flag, but you can echo the command.

find . -name "*.bak" | xargs -I {} echo rm {}

Notes

  • Empty Input: If input is empty, xargs (GNU) might still run the command once without arguments (e.g., just rm). Use --no-run-if-empty (or -r) to prevent this.
    find . -name "*.nonexistent" | xargs -r rm