SyntaxStudy
Sign Up
Linux / Bash xargs and Command Substitution
Linux / Bash Beginner 1 min read

xargs and Command Substitution

The `xargs` command reads items from stdin and uses them as arguments to another command. This bridges the gap between commands that produce output and commands that expect arguments rather than stdin. For example, `find` produces a list of filenames and `xargs` feeds them to `rm`, `chmod`, or any other command. Command substitution embeds the output of one command into another using `$(command)` or the older backtick syntax. The shell executes the inner command, captures its output, and substitutes it in place. This is used constantly in scripts to capture command results into variables, build dynamic arguments, or embed date stamps into filenames. Arithmetic expansion with `$((expression))` evaluates integer arithmetic inline in the shell. Combined with command substitution and pipes, these features let you build sophisticated one-liners and scripts that compute values, process output, and construct complex command strings dynamically without leaving the shell.
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"