How to Use xargs Command in Linux: Syntax and Examples
The
xargs command in Linux reads input from standard input and builds command lines to execute other commands with that input as arguments. It is useful to handle output from commands like find or echo and pass them as arguments to another command efficiently.Syntax
The basic syntax of xargs is:
xargs [options] [command]
Here:
commandis the command to run with the input as arguments (default isecho).optionsmodify howxargsprocesses input and runs commands.
bash
xargs [options] [command]
Example
This example shows how to use xargs to delete files listed by find. It reads file names from find and passes them to rm to delete:
bash
find . -name '*.tmp' -print | xargs rm -f
Common Pitfalls
Common mistakes when using xargs include:
- Failing to handle file names with spaces or special characters, which can break argument parsing.
- Not using
-0option withfind -print0to safely handle all file names. - Assuming
xargsalways runs the command once; it may run multiple times if input is large.
Correct way to handle spaces safely:
bash
find . -name '*.tmp' -print0 | xargs -0 rm -f
Quick Reference
| Option | Description |
|---|---|
| -0 | Input items are separated by null characters (safe for spaces and special characters) |
| -n | Use at most |
| -p | Prompt before running each command |
| -I | Replace occurrences of |
| -t | Print the command before executing it |
Key Takeaways
Use
xargs to convert input from standard input into command arguments.Always use
-0 with find -print0 to safely handle file names with spaces.You can control how many arguments
xargs passes per command with -n.Use
-I to replace a placeholder in the command with input items.Test commands with
-t to see what xargs will run before execution.