Using fzf as a quick CLI UI

fzf is an awesome tool, it has many uses. One of them is to use it to create it as a tool to create UIs in your terminal.

UIs you say? Yeah, there are no buttons or windows, but you can make a quick search/select -> do action UI with one single line.

For this purpose we only need to know one of the things that fzf does, which is that it receives a list of strings separated by \n and allows you to select one of them, fzf then prints it to STDOUT.

That’s all you need to know, while it doesn’t sound like much, it’s actually a killer feature because you can use fzf to pick items from a list and use that item as the input for another command. Can you feel the power of it already? Well, I can, so I’ll just show you some examples which will hopefully blow your mind in the most positive sense possible.

Change directory interactively

The simplest example that I can think of is to change the directory. The first step is to figure out how to get a list of directory names in the current directory:

$ find -maxdepth 1 -type d

While this find shows us all directories in our current directory, it also shows us all the hidden directories too, but I’ll leave that as an exercise for the reader ;). Alternatively, if you have fd installed, use fd --maxdepth 1 -t d (much easier to figure out how to use than find and faster).

Our action is to “change directory” into that folder, which translated into CLI speak, cd, now let’s just put it all together:

$ cd $(find -maxdepth 1 -type d | fzf)

Boom! If you run that command, you get a menu to select a directory and when you press Enter, you cd into it.

Git add interactive

Tired of doing git status followed by git add <copy pasta filename>? I am, I hate using the mouse and using tmux’s copy paste is way too many keystrokes.

Step 1, figure out our list of options, we want to see all the filenames that we can use for git add -ing.

# cut only shows the filename without the status
# sed makes sure we can add files with spaces
$ git status -s | cut -c4- | sed 's/\"//g'

Since we want to git add the files, the complete line to interactively git add files is:

$ git add $(git status -s | cut -c4- | sed 's/\"//g' | fzf)

BONUS: fzf allows you to select more than one result using --multi, if you add that to the example, you can now git add multiple files :D.

I hope I made you as excited about fzf as I am.