How to Use xargs in Bash: Syntax, Examples, and Tips
In bash,
xargs reads items from standard input and builds command lines to execute them. It is useful to convert output from one command into arguments for another, especially when handling lists or multiple inputs.Syntax
The basic syntax of xargs is:
xargs [options] [command]
Here:
commandis the command to run with arguments built from input (default isecho).optionsmodify how input is processed, like specifying delimiters or max arguments.
bash
xargs [options] [command]
Example
This example shows how to use xargs to delete files listed by find. It converts the list of files into arguments for rm:
bash
find . -name '*.tmp' | xargs rmCommon Pitfalls
Common mistakes include:
- Failing to handle spaces or special characters in input filenames.
- Using
xargswithout-0when input is null-separated. - Assuming
xargsruns the command once per input item instead of batching.
To handle spaces safely, use:
bash
find . -name '*.tmp' -print0 | xargs -0 rm
Quick Reference
| Option | Description |
|---|---|
| -0 | Input items are separated by null characters (safe for spaces) |
| -n | Use at most |
| -I | Replace occurrences of |
| -p | Prompt before running each command |
| -r | Do not run command if no input |
Key Takeaways
Use
xargs to convert input lists into command arguments efficiently.Always handle spaces and special characters safely with
-0 and null-separated input.Combine
xargs with commands like find to process many files at once.Use options like
-n and -I to control argument batching and replacement.Test commands with
-p to avoid accidental destructive actions.