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 --process-slot-var gives every parallel job a worker number

Xargs
~/tips/tip-xargs-process-slot-var-worker-number

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'

Sets an environment variable in each parallel xargs job, holding the slot number it runs in.

With xargs -P I sometimes want to know which worker is busy with which item, for instance to spread jobs over a few output folders or devices. GNU xargs has a switch for that.

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'

--process-slot-var=VAR sets the environment variable VAR in every child process. With -P3 there are three slots, numbered from 0. The output order of parallel jobs is not fixed, so I piped it through sort. The result:

slot 0 got a
slot 0 got d
slot 1 got b
slot 1 got f
slot 2 got c
slot 2 got e

Each slot handled two items. That is the useful part: the slot number is a small, stable label you can use for a scratch directory such as /tmp/work-$SLOT, or as a device index you pass to a tool.

Notice the $0 in the sh -c script. With sh -c 'script' arg the first argument becomes $0, so that is where xargs puts each item. Quoting the script in single quotes matters, otherwise your own shell expands $SLOT before xargs even starts, and it is empty.

The caveat: I would not count on a particular item landing in a particular slot. Use the number as a label for a place to work in, not to decide what a job does.

Further reading: xargs options (GNU findutils manual)

More Xargs tips 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: printf 'x\ny\n' | xargs -t touch All Xargs tips (12) All topics

Link