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 exits with 123 when one of its commands failed

Xargs
~/tips/tip-xargs-exit-status-123

find . -name '*.gz' -print0 | xargs -0 -n 1 gzip -t

Explains xargs exit codes, so a script can tell whether every command it ran succeeded.

xargs runs a command many times, but it gives back one exit code. Knowing what that code means is how a script finds out that one of the runs went wrong.

find . -name '*.gz' -print0 | xargs -0 -n 1 gzip -t
echo $?

If every run of gzip -t worked, xargs exits with 0. If any run failed with a status from 1 to 125, xargs keeps going with the rest and exits with 123 at the end. Two runs where one fails give 123.

I think a few other codes are worth knowing. When a command exits with 255, xargs stops right away and returns 124; that’s a way for a script to say “abort everything”. 127 means the command wasn’t found, and 126 that it was found but couldn’t be run. A command killed by a signal gives 125.

So in a script, this is enough to notice a failure:

if ! find . -name '*.gz' -print0 | xargs -0 -r gzip -t; then
  echo 'at least one archive is damaged' >&2
fi

Two limits. The code says something failed, not which run, so let the command print its own errors. And in a pipeline, $? is the status of the last command; if find fails before it, you only see it with set -o pipefail.

Further reading: xargs(1) manual page, GNU findutils manual: Invoking xargs

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 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