xargs Command with Examples

Learn how to use xargs command effectively with practical examples

Featured image

image reference link



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

2️⃣ Using with ls command

ls *.log | xargs rm

3️⃣ Combining find and wc commands

find . -type f -name "*.txt" -print0 | xargs -0 wc -l

4️⃣ Processing standard input

echo "one two three" | xargs -n 1 echo "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



Important Options



Reference