Xargs for Parallel Execution
Uses xargs to build and execute commands from standard input with parallel execution, argument batching, and null-delimiter handling for safe processing.
Code
#!/usr/bin/env bash
set -euo pipefail
# Basic xargs: pass input as arguments
echo "file1 file2 file3" | xargs mkdir -p
# One argument per command
printf "a\nb\nc\n" | xargs -I{} echo "Processing: {}"
# Parallel execution (-P)
printf "1\n2\n3\n4\n" | xargs -P4 -I{} sh -c "echo Job {} starting; sleep 1; echo Job {} done"
# Null-delimited for safe filenames
find /etc -maxdepth 1 -name "*.conf" -type f -print0 2>/dev/null |
xargs -0 -I{} echo "Found: {}"
# Batch arguments
printf "1\n2\n3\n4\n5\n6\n" | xargs -n2 echo "Pair:"
# Parallel with progress
process_file() {
local file=$1
echo "Processing: $file"
sleep 0.5
echo "Done: $file"
}
export -f process_file
find /etc -maxdepth 1 -name "*.conf" -type f 2>/dev/null |
head -5 |
xargs -P4 -I{} bash -c "process_file "$@"" _ {}
# Dry run: show commands without executing
printf "file1\nfile2\nfile3\n" | xargs -t -I{} echo "Would process: {}"
# Handle large argument lists
find /usr -type f -name "*.so" 2>/dev/null |
xargs -n100 -I{} sh -c "echo Processing batch; ls -la {}" 2>/dev/null |
head -5
# Cleanup
rm -rf file1 file2 file3xargs converts stdin to command arguments. -I{} defines a replace string, -P N runs N processes in parallel, -n N limits arguments per command, -0 handles null-delimited input (safe for filenames with spaces), -t prints commands before executing (dry run). -P with -I enables parallel job processing. Use export -f to make functions available to xargs subprocesses.
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
Report a problem with this exampleOpens a pre-filled issue on GitHub.