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 -r skips the command when there is no input at all

Xargs
~/tips/tip-shell-xargs-r-no-run-if-empty

docker ps -aq --filter status=exited | xargs -r docker rm

Stops xargs from running the command when the pipeline before it produced no input.

There’s one xargs option I think should have been the default. Normally xargs runs your command once even when nothing comes in on standard input. Most of the time that just means an error message. Sometimes it means the command does something you didn’t ask for.

The GNU xargs option -r (long form --no-run-if-empty) stops that. If the input holds nothing but blanks, the command doesn’t run:

docker ps -aq --filter status=exited | xargs -r docker rm

That removes every container with the status exited. When there are none, docker ps prints nothing and xargs with -r simply does nothing. Without the flag, xargs calls docker rm with no arguments and you get an error instead of a quiet exit, which is noise in a cron job or a script on an Unraid box that runs every night.

The quiet error is the harmless case. The nasty case is a command that does something sensible when it gets no arguments. ls without arguments lists the current folder instead of the files you meant, and du -sh without arguments reports on the folder you happen to be in. If your pipeline finds no files and xargs calls the command anyway, you end up acting on the wrong thing. With -r an empty result stays an empty result.

My advice is to add -r to any xargs line in a script where empty input is possible, which is most of them. It combines fine with the other options, so find ... -print0 | xargs -0 -r rm works too.

The caveat: it’s a GNU extension. On Linux that’s what you have, but if a script also needs to run on a system with a different xargs, check its man page first. And -r only helps when the input is completely empty. A single stray blank line counts as blanks, so it’s skipped, but any real text, even a wrong one, still runs the command.

Further reading: xargs(1) manual page

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