xargs — Run Commands on Piped Input
What is xargs?
xargs reads items from stdin (usually filenames) and runs a command with those items as arguments. Bridges find (and other list producers) with commands that don’t read stdin.
find ... → list of files → xargs → grep/cat/chmod on each file
OSCP use:
find ... | xargs grep -l password, bulk file operations, parallel scans.
Syntax
find ... | xargs COMMAND
find ... | xargs -I {} COMMAND {}
echo "a b c" | xargs -n1📌 Common Flags
| Flag | Description |
|---|---|
-0 | Null-delimited input (use with find -print0) — handles spaces in filenames |
-I {} / -i | Replace {} with input item in command |
-n N | Max N arguments per command |
-P N | Run N processes in parallel |
-t | Print command before executing |
-p | Prompt before each command |
-r / --no-run-if-empty | Don’t run if input empty |
📌 Basic Examples
# Grep all .conf files for password
find / -name "*.conf" 2>/dev/null | xargs grep -l "password" 2>/dev/null
# Grep all PHP for creds
find /var/www -name "*.php" 2>/dev/null | xargs grep -i "password" 2>/dev/null
# List details of all SUID files
find / -perm -4000 -type f 2>/dev/null | xargs ls -la 2>/dev/null
# Delete all .tmp files (careful!)
find /tmp -name "*.tmp" | xargs rm -f📌 Safe Handling of Spaces in Filenames
# BAD — breaks on spaces
find . -name "*.txt" | xargs cat
# GOOD — null-delimited
find . -name "*.txt" -print0 | xargs -0 cat📌 -I {} — Custom Placement
find . -name "*.log" | xargs -I {} sh -c 'echo "=== {} ==="; head -5 {}'
find / -name "*.conf" 2>/dev/null | xargs -I {} grep -H "password" {}📌 Parallel Execution
# 4 parallel grep processes
find /var/www -name "*.php" 2>/dev/null | xargs -P4 -n1 grep -l "eval(" 2>/dev/null📌 xargs vs -exec
| Method | Notes |
|---|---|
find ... | xargs cmd | Flexible, parallel with -P, handles large lists |
find ... -exec cmd {} \; | One file per exec (slower) |
find ... -exec cmd {} + | Batch like xargs (efficient) |
📌 Quick Cheat Sheet
find / -name "*.conf" 2>/dev/null | xargs grep -l "pass" 2>/dev/null
find . -name "*.txt" -print0 | xargs -0 cat
find . -name "*.sh" | xargs chmod +x
find . -name "*.php" | xargs -I {} grep -H "password" {}
echo "host1 host2" | xargs -n1 -P2 nmap -sV