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 -o lets an interactive program like vim work from a pipe

Xargs
~/tips/tip-xargs-o-open-tty

grep -l 'TODO' *.py | xargs -o vim

Connects the command xargs starts to your terminal, so editors and prompts work normally.

Opening every file that grep found in an editor sounds simple: pipe the names to xargs vim. Then vim complains that input is not from a terminal, and the terminal ends up in a weird state.

The command that xargs starts gets the same standard input as xargs, and that was the pipe with file names. -o (long form --open-tty) reconnects it to your terminal first:

grep -l 'TODO' *.py | xargs -o vim

Now vim opens all files normally, and :next moves through them. It works for anything that needs the keyboard: xargs -o rm -i asks per file, and a script with a read prompt gets your answer.

Without -o, the workaround you see everywhere is a subshell: vim $(grep -l TODO *.py). I think that’s fine until a file name has a space in it, and xargs with -d '\n' handles those better.

GNU xargs 4.9, BusyBox xargs and the one on macOS all list the option, but older GNU versions don’t have it. Also, it only makes sense with a terminal around; in a cron job there’s no terminal to open, so the command fails instead of quietly reading nothing.

Further reading: xargs(1) manual page, FreeBSD 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' 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