Linux / Bash
Beginner
1 min read
xargs and Command Substitution
Example
# xargs: pass find results to rm
find /tmp -name "*.tmp" | xargs rm -f
# xargs: limit to N arguments at a time
find . -name "*.log" | xargs -n 1 gzip
# xargs: run N processes in parallel
find . -name "*.jpg" | xargs -P 4 -I {} convert {} -resize 800x {}_thumb.jpg
# xargs with null delimiter (handles spaces in filenames)
find . -name "*.txt" -print0 | xargs -0 wc -l
# xargs: prompt before executing each command
find . -name "*.bak" | xargs -p rm
# ---- Command substitution $() ----
# Capture output into a variable
TODAY=$(date +%Y-%m-%d)
echo "Today is $TODAY"
# Use in a filename
tar -czf "backup_${TODAY}.tar.gz" /etc/
# Nested command substitution
KERNEL=$(uname -r)
ARCH=$(uname -m)
echo "Running kernel $KERNEL on $ARCH"
# Count files returned by find
FILE_COUNT=$(find /var/log -name "*.log" | wc -l)
echo "Found $FILE_COUNT log files"
# Backtick style (older, avoid in new scripts)
HOSTNAME=`hostname`
# ---- Arithmetic expansion ----
echo $((2 + 3)) # 5
echo $((10 * 1024)) # 10240
DISK_KB=$(du -s /var/log | cut -f1)
DISK_MB=$(( DISK_KB / 1024 ))
echo "Log directory: ${DISK_MB} MB"
Related Resources
Linux / Bash Reference
Complete tag & property list
Linux / Bash How-To Guides
Step-by-step practical guides
Linux / Bash Exercises
Practice what you've learned
More in Linux / Bash