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 -a reads the list from a file and keeps standard input free

Xargs
~/tips/tip-xargs-a-read-file

xargs -a hosts.txt -n 1 ssh-keygen -R

Takes the items from a file so the command that xargs runs can still use the keyboard.

Normally xargs reads its list from standard input. That has a side effect people run into sooner or later: the command it starts inherits that input, which is already used up.

xargs -a hosts.txt -n 1 ssh-keygen -R

-a (long form --arg-file) reads the items from a file instead. xargs -a list echo got prints got x y, the same as piping the file in.

The difference shows up with commands that read from standard input themselves. If you pipe into xargs, those commands get nothing useful from stdin, and interactive ones like an editor or a program that asks a question misbehave. With -a, standard input stays connected to your terminal, so the command can still read from it.

I also think it makes the line a bit easier to read when the list is just a file, instead of starting with cat file |.

The file is read the same way as a pipe, so all the usual rules apply: blanks split items and quotes are special unless you add -d '\n' or use -0 with a NUL-separated file. And not every xargs has -a. GNU and the BusyBox one in Alpine do, the macOS one doesn’t, so for scripts that must run everywhere a redirect, xargs ... < list.txt, does the same except for the stdin part.

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