xargs Command
The xargs command in Linux is a powerful utility that reads items from standard input, 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 using these items as arguments. It's particularly useful for building and executing commands when the input comes from another command's output.
Syntax
Description
xargs is used to execute a command with arguments that are read from standard input. This is crucial because many commands do not accept input directly from a pipe (|) as arguments. xargs bridges this gap by converting standard input into arguments for a specified command.
Common uses include:
- Executing commands on a list of files generated by another command (e.g.,
find) - Processing multiple items from a list in a loop-like fashion
- Building complex command lines dynamically
- Handling filenames with spaces or special characters safely
Common Options
| Option | Description |
|---|---|
-0, --null |
Input items are terminated by a null character instead of by whitespace. Useful with `find -print0`. |
-n count |
Use at most `count` arguments per command line. |
-P max-procs |
Run at most `max-procs` processes at a time; default is 1. |
-I replace-str |
Replace occurrences of `replace-str` in the initial arguments with names read from standard input. |
-t, --no-run-if-empty |
Print the command and its arguments to standard error before executing it. |
-r, --no-run-if-empty |
If the standard input contains only blanks or no characters, do not run the command. |
Examples
Delete files found by find
Finds all files ending with '.tmp' and deletes them safely, even if filenames contain spaces.
Copy files to a new directory
Copies all '.txt' files to the '/backup/texts/' directory.
Execute command for each line of input
Reads server names from 'servers.txt' and attempts to SSH into each one.
Process files in parallel
Resizes all '.png' images in parallel using 4 processes.
Combine multiple lines into a single command
Outputs: Combined arguments: arg1 arg2 arg3