Xargs Parallel Job Control Batching
Process file batches in parallel with xargs -P and -N, controlling concurrency, preserving order, and capping memory.
Code
#!/usr/bin/env bash
set -euo pipefail
readonly MAX_JOBS=4
readonly BATCH_SIZE=10
process_batch() {
local batch_number=$1
shift
echo "batch ${batch_number}: 处理 $# 个文件"
for file in "$@"; do
local size
size=$(stat -c%s "$file" 2>/dev/null || stat -f%z "$file")
printf '%s\t%d bytes\n' "$(basename "$file")" "${size}"
done
}
export -f process_batch
# -P 控制并发数,-N 每次传一批参数,--keep-order 稳定输出
find ./data -name '*.log' -type f -print0 \
| xargs -0 -P "${MAX_JOBS}" -n "${BATCH_SIZE}" \
bash -c 'process_batch "$@"' _ \
| sort
# 不分批的高并发形态:一文件一任务
find ./data -name '*.small' -type f -print0 \
| xargs -0 -P "${MAX_JOBS}" -I{} \
sh -c 'gzip -k "{}" && echo "compressed {}"'
# 失败可见性:--no-run-if-empty 防空输入报错
find ./data -name '*.missing' -type f -print0 \
| xargs -0 -r --no-run-if-empty echo "found"
How the snippet works
The shebang line is backed by set -euo pipefail: first failure stops the run, unset variables are errors, and a pipeline fails if any stage fails.
The work is delegated to readonly, find, bash and sh, chained through 6 pipes so each stage’s output feeds the next.
A helper function (process_batch) keeps the repeated logic out of the main flow.
Watch out for
- The pipeline is 6 stages deep — when it misbehaves, split the pipe and test the stages separately.
Key statements worth quoting
for file in "$@"; do
local size
size=$(stat -c%s "$file" 2>/dev/null || stat -f%z "$file")
| xargs -0 -P "${MAX_JOBS}" -n "${BATCH_SIZE}" \
bash -c 'process_batch "$@"' _ \
| sort
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.Cache-Control BuilderCompose a valid Cache-Control header from directives such as no-store, private, max-age, and immutable.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.
FAQ
- Does the script stop on the first error?
- Yes — `set -euo pipefail` aborts on the first failing command, treats unset variables as errors, and fails the whole pipeline if any stage fails. Nothing continues half-broken.
- Which external commands does the script rely on?
- `readonly`, `find`, `bash`, `sh` must be available on the PATH environment variable; everything else is shell built-in syntax.
Report a problem with this exampleOpens a pre-filled issue on GitHub.