3 min to read
xargs Command with Examples
Learn how to use xargs command effectively with practical examples

Overview
xargs is a Unix and Linux command utility that reads data from standard input and passes it as arguments to other commands.
What is xargs?
xargs takes input from a pipe ( | ) and passes that input as arguments to another command.
This allows for processing more data than a single command could handle on its own.
Basic Usage
1️⃣ Using with find command
find . -name '*.txt' | xargs rm
- This command finds all .txt files in the current directory and deletes them.
2️⃣ Using with ls command
ls *.log | xargs rm
- This command finds and deletes all .log files in the current directory.
3️⃣ Combining find and wc commands
find . -type f -name "*.txt" -print0 | xargs -0 wc -l
- This command counts the lines in all .txt files.
4️⃣ Processing standard input
echo "one two three" | xargs -n 1 echo "Word:"
- This adds “Word:” prefix to each input word.
Advanced Usage
1️⃣ Kubernetes Pod Management
# Delete Error state pods
kubectl get po -n <namespace> | grep Error | awk '{print $1}' | xargs kubectl delete po -n <namespace>
# Delete Evicted state pods
kubectl get po -n <namespace> | grep Evicted | awk '{print $1}' | xargs kubectl delete po -n <namespace>
# Delete CrashLoopBackOff state pods
kubectl get po -n <namespace> | grep CrashLoopBackOff | awk '{print $1}' | xargs kubectl delete po -n <namespace>
2️⃣ Docker Container Management
sudo docker ps -a | grep Exit | cut -d ' ' -f 1 | xargs sudo docker rm
This command removes all containers in Exit state.
Parallel Processing with xargs
1️⃣ Sequential Execution
time for i in $(seq 1 5); do echo $[$RANDOM % 5 + 1]; done | xargs -I{} echo "sleep {}; echo 'Done! {}'" | xargs -I{} bash -c "{}"
# Sample output:
Done! 4
Done! 3
Done! 4
Done! 2
Done! 3
real 0m16.034s
user 0m0.033s
sys 0m0.005s
2️⃣ Parallel Execution (using -P option)
time for i in $(seq 1 5); do echo $[$RANDOM % 5 + 1]; done | xargs -I{} echo "sleep {}; echo 'Done! {}'" | xargs -P5 -I{} bash -c "{}"
# Sample output:
Done! 1
Done! 1
Done! 2
Done! 4
Done! 4
real 0m4.007s
user 0m0.016s
sys 0m0.003s
- Execution Time Comparison:
- Sequential: ~16 seconds
- Parallel: ~4 seconds
Important Options
-n [number]
: Specify the number of arguments to pass at once-I [placeholder]
: Replace occurrences of placeholder in the command-0 or -null
: Input items are terminated by null character-P [number]
: Number of processes to run in parallel
Comments