xargs — Execute Commands from Input
xargs reads input and passes it as arguments to a command.
Why xargs?
Some commands don't accept stdin as arguments. xargs bridges the gap.
Basic usage
find . -name "*.txt" | xargs cat # Cat all .txt files
find . -name "*.log" | xargs rm # Delete all .log files
echo "file1 file2 file3" | xargs ls -la
Safer with null delimiter
find . -name "*.txt" -print0 | xargs -0 rm
-print0 and -0 use null bytes as delimiters — safe for filenames with spaces.
Parallel execution
cat urls.txt | xargs -P 4 wget # Download 4 at a time
find . -name "*.jpg" | xargs -P 8 -I{} convert {} {}.png
-I{} placeholder
find . -name "*.txt" | xargs -I{} cp {} /backup/{}
cat names.txt | xargs -I{} echo "Hello, {}!"
Limit arguments per invocation
xargs -n 1 command # One arg per command call
xargs -n 3 command # Three args per call
Practical examples
# Compress all logs older than 7 days
find /var/log -name '*.log' -mtime +7 | xargs gzip
# Count lines in all Python files
find . -name '*.py' | xargs wc -l
# Search for text in all .conf files
find /etc -name '*.conf' | xargs grep -l 'ServerName'