brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: xargs -P runs commands in parallel, no GNU parallel needed

Xargs
~/tips/tip-shell-xargs-parallel-p

find . -name '*.png' -print0 | xargs -0 -n 1 -P 4 optipng

Runs a command on several inputs at the same time instead of one after another.

A loop that processes files one at a time leaves most of your CPU idle. xargs can fan the work out and it is already installed.

-P N (--max-procs) runs up to N processes at a time; the default is 1. Combine it with -n 1, which gives each process one argument, and with NUL-separated input.

find . -name '*.png' -print0 | xargs -0 -n 1 -P 4 optipng
printf '%s\n' host1 host2 host3 | xargs -n 1 -P 3 ping -c 1

On Linux, -P 0 means as many as possible, and $(nproc) is a sensible number for CPU-bound jobs. For network or disk work the best value is lower and depends on the machine.

The caveat is output. The man page says that if several processes print to standard output, the order is indeterminate, and lines can end up mixed. If you need clean output, have each job write to its own file. Also, if one command fails, xargs finishes the rest and then exits with 123, so check the exit code instead of assuming it all went well. Do not use it for commands that depend on each other.

Further reading: xargs(1) man page, On this site: find -print0 | xargs -0 survives file names with spaces, On this site: timeout stops a command that hangs

More Xargs tips printf '%s\n' a b c d e f | xargs -n1 -P3 --process-slot-var=SLOT sh -c 'echo "slot $SLOT got $0"; sleep 0.2' grep -l 'TODO' *.py | xargs -o vim find . -name '*.orig' -print0 | xargs -0 -p rm find . -name '*.gz' -print0 | xargs -0 -n 1 gzip -t printf 'a b\nc d\n' | xargs -L 1 echo line: All Xargs tips (12) All topics

Link