martes, 26 de septiembre de 2023

Naive option picker (fzf) in pure shell

 I've been a big fan of option pickers since.... forever. I've used ratmenu, ratmen, dmenu, dzen, percol, fzf, helm, vertico, consul...


For me, it's so fundamental that I need this functionality in every piece of code/script I write.

Finally I got to a working version of a very small version of it.

As always, pure shell, but with some advanced features can give you a succint function that works predictably.  The /dev/tty part was the trickiest to get working, as I didn't know how to get input from a pipe, and at the same time be able to read data from the keyboard.



# fzf is either fzf or a naive version of it
# the input is a sed line number, so it can be
# single number: 42
# range: 1,10
# separate lines: 10p;50p
mute command -v fzf ||
fzf() {
local in=$(cat)
for p in "${@}"; do
[ "$p" = "-0" ] && [ "$(echo "$in" | wc -l)" -eq 1 ] && [ "" = "$in" ] && return 1
[ "$p" = "-1" ] && [ "$(echo "$in" | wc -l)" -eq 1 ] && [ "" != "$in" ] && echo "$in" && return
done
# https://superuser.com/questions/1748550/read-from-stdin-while-piping-to-next-command
cat -n <(echo "$in") >/dev/tty
read -n num </dev/tty
echo "$in" | sed -n "${num}p"
}
view raw fzf.sh hosted with ❤ by GitHub

No hay comentarios: