Some tools accept many arguments at once. xargs -n groups input words into batches before running the command.

Program

Play the script to choose the batch size and see how the arguments are grouped.

batch_size
xargs_batch_plan.sh
Replay: real traced execution (multi-file project)
#!/usr/bin/env bash

batch_size=2
items=("api" "worker" "web")
command="xargs -n $batch_size restart"
if [ "$batch_size" -eq 2 ]; then
    groups="api worker|web"
else
    groups="api worker web"
fi
echo "$command -> $groups"
#!/usr/bin/env bash

batch_size=3
items=("api" "worker" "web")
command="xargs -n $batch_size restart"
if [ "$batch_size" -eq 2 ]; then
    groups="api worker|web"
else
    groups="api worker web"
fi
echo "$command -> $groups"
  1. batch_size ← 2

    3batch_size=24items=("api" "worker" "web")
    values this step2batch_size
  2. items ← api worker web

    3batch_size=24items=("api" "worker" "web")5command="xargs -n $batch_size restart"
    values this stepapi worker webitems
  3. command ← xargs -n 2 restart

    4items=("api" "worker" "web")5command="xargs -n $batch_size restart"6if [ "$batch_size" -eq 2 ]; then
    values this stepxargs -n 2 restartcommand2batch_size
  4. if [ "$batch_size" -eq 2 ]; then

    5command="xargs -n $batch_size restart"6if [ "$batch_size" -eq 2 ]; then7    groups="api worker|web"
    values this step2batch_size
  5. groups ← api worker|web

    6if [ "$batch_size" -eq 2 ]; then7    groups="api worker|web"8else
    values this stepapi worker|webgroups
  6. echo "$command -> $groups"

    10fi11echo "$command -> $groups"
    outputxargs -n 2 restart -> api worker|web
    values this stepxargs -n 2 restartcommandapi worker|webgroups
  1. batch_size ← 3

    3batch_size=34items=("api" "worker" "web")
    values this step3batch_size
  2. items ← api worker web

    3batch_size=34items=("api" "worker" "web")5command="xargs -n $batch_size restart"
    values this stepapi worker webitems
  3. command ← xargs -n 3 restart

    4items=("api" "worker" "web")5command="xargs -n $batch_size restart"6if [ "$batch_size" -eq 2 ]; then
    values this stepxargs -n 3 restartcommand3batch_size
  4. if [ "$batch_size" -eq 2 ]; then

    5command="xargs -n $batch_size restart"6if [ "$batch_size" -eq 2 ]; then7    groups="api worker|web"
    values this step3batch_size
  5. groups ← api worker web

    8else9    groups="api worker web"10fi
    values this stepapi worker webgroups
  6. echo "$command -> $groups"

    10fi11echo "$command -> $groups"
    outputxargs -n 3 restart -> api worker web
    values this stepxargs -n 3 restartcommandapi worker webgroups
xargs `xargs` converts input words into command arguments.
batch size `-n` controls how many arguments go into each command run.
grouping Changing the batch size changes the command grouping without changing the input list.