Parallel Batch Processing With xargs

Run CPU-bound jobs in parallel with xargs -P, cap concurrency to core count, and keep per-job logs separated for post-mortem.

BashCli Tooling

Code

snippet
#!/usr/bin/env bash
set -euo pipefail

readonly JOBS_DIR="${1:?jobs directory required}"
readonly PARALLEL="${PARALLEL:-$(nproc)}"

mkdir -p logs

# -P 并发上限、-n 每批一个参数;-I{} 用于文件名替换
find "${JOBS_DIR}" -name '*.job' -print0 |
  xargs -0 -n1 -P "${PARALLEL}" -I{} bash -c '
    job="$1"
    name="$(basename "${job}" .job)"
    log="logs/${name}.log"
    {
      echo "=== ${name} started $(date -Is)"
      bash "${job}"
      echo "=== ${name} exited $?"
    } > "${log}" 2>&1
  ' _

echo "done; logs in $(pwd)/logs"

Inside the snippet

set -euo pipefail removes the shell’s usual optimism — errors abort, empty variables abort, hidden pipeline failures abort.

The work is delegated to readonly, mkdir, find, xargs and bash, chained through 1 pipe so each stage’s output feeds the next.

The script leans on parameter expansion 10 times, using forms like ${var:-default} so defaults, trimming, and casing happen inside the shell with no external tool.

The key statements, annotated

readonly PARALLEL="${PARALLEL:-$(nproc)}"
find "${JOBS_DIR}" -name '*.job' -print0 |
  xargs -0 -n1 -P "${PARALLEL}" -I{} bash -c '
name="$(basename "${job}" .job)"

Interactive Tools for This Topic

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`, `mkdir`, `find`, `xargs`, `bash` must be available on the PATH environment variable; everything else is shell built-in syntax.