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 -I {} puts each input line exactly where you want it in the command

Xargs
~/tips/tip-shell-xargs-i-placeholder

find . -maxdepth 1 -name '*.conf' | xargs -I {} cp {} {}.bak

Places each input line at a chosen spot in the command, not just at the end.

By default xargs glues the input to the end of your command. That’s fine for rm, but plenty of commands want the file name somewhere else, or twice. cp is the classic example: the source goes first and the destination last.

-I lets you pick a placeholder, and xargs replaces it with each input line. {} is the usual choice:

find . -maxdepth 1 -name '*.conf' | xargs -I {} cp {} {}.bak

For every .conf file in the current folder that runs cp app.conf app.conf.bak, with the name filled in on both spots. You can use any string as the placeholder, so -I FILE works as well if you find that easier to read.

Another case where I’d reach for it: a list of names in a text file, one per line, that each needs a folder. xargs -I {} mkdir -p /mnt/user/appdata/{}/config < apps.txt builds the whole tree in one go, with the name in the middle of the path where plain xargs can’t put it.

A few things change when you use -I, and the man page lists them. Input is split on newlines only, so a line with spaces in it stays one item. That’s nice for names with spaces. It also implies -L 1, which means xargs runs the command once per input line instead of batching many arguments into one call. For a few dozen files you won’t notice. For tens of thousands it’s a lot slower than plain xargs, and then find -exec ... + or plain xargs without -I is the better pick.

The caveat: newline splitting still isn’t safe for file names that contain a newline. Rare, but possible. When you can’t rule that out, use find -print0 with xargs -0, which works together with -I too.

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