Privacy Policy
© 2025 linux101.dev

xargs Command Cheatsheet

The xargs command reads items from standard input, separated by blanks (which can be `space`, `tab`, `newline`), and executes a specified command using these items as arguments. It's a fundamental tool for building pipelines and handling lists of files.

Why `xargs`?

`xargs` is necessary because many commands (like `rm`, `cp`, `mv`) are not designed to take a list of items from standard input. It acts as a bridge, converting the output of one command into the arguments for another.

Common Usage

CommandDescription
find . -name "*.txt" | xargs rmFinds all files with a `.txt` extension and then uses `xargs` to pass those filenames as arguments to the `rm` command, deleting them.
find . -name "*.log" | xargs grep "ERROR"Finds all `.log` files and then uses `xargs` to pass those filenames as arguments to `grep`, which searches for the word "ERROR" within each file.
find . -name "*.log" -print0 | xargs -0 grep "ERROR"Finds all `.log` files and separates each found filename with a NULL sign ('\0') and then uses `xargs` (which uses a NULL character as filenames separator due to -0) to pass those filenames as arguments to `grep`, and searches for the word "ERROR" within each file.
ls -1 *.bak | xargs -I {} mv {} {}.oldA more advanced example:
  • ls -1 *.bak: Lists all `.bak` files, one per line.
  • -I {}: Tells `xargs` to use `{}` as a placeholder for each input line.
  • mv {} {}.old: For each `.bak` file, it renames it with a `.old` extension.

Key `xargs` Options

OptionDescription
-I [REPLACEMENT]Specifies a replacement string that will be replaced by the input string in the command. This is essential when a command needs to be executed multiple times with a single argument each time.
-n [MAX_ARGS]Specifies the maximum number of arguments to be passed to the command per execution. For example, `xargs -n 2` will pass two arguments at a time.
-P [MAX_PROCS]Runs commands in parallel. Specifies the maximum number of processes to run at once.
-pPrompts the user for confirmation before executing each command.
-0Input items are terminated by a null character instead of whitespace. This is crucial for handling filenames with spaces or special characters, and is often used with find -print0.