Post

Basics of fzf

fzf is a general-purpose command-line fuzzy finder. It’s an interactive Unix filter for command-line that can be used with any list; files, command history, processes, hostnames, bookmarks, git commits, etc.

Installation

fzf project consists of the following components:

  • fzf executable
  • fzf-tmux script for launching fzf in a tmux pane
  • Shell extensions
    • Key bindings (CTRL-T, CTRL-R, and ALT-C) (bash, zsh, fish)
    • Fuzzy auto-completion (bash, zsh)
  • Vim/Neovim plugin

You can download fzf executable alone if you don’t need the extra stuff.

Using Homebrew

You can use Homebrew (on macOS or Linux) to install fzf.

1
2
3
4
brew install fzf

# To install useful key bindings and fuzzy completion:
$(brew --prefix)/opt/fzf/install

fzf is also available via MacPorts: sudo port install fzf

Using git

Alternatively, you can “git clone” this repository to any directory and run install script.

1
2
git clone --depth 1 https://github.com/junegunn/fzf.git ~/.fzf
~/.fzf/install

Using Linux package managers

Package ManagerLinux DistributionCommand
APKAlpine Linuxsudo apk add fzf
APTDebian 9+/Ubuntu 19.10+sudo apt install fzf
Conda conda install -c conda-forge fzf
DNFFedorasudo dnf install fzf
NixNixOS, etc.nix-env -iA nixpkgs.fzf
PacmanArch Linuxsudo pacman -S fzf
pkgFreeBSDpkg install fzf
pkginNetBSDpkgin install fzf
pkg_addOpenBSDpkg_add fzf
PortageGentooemerge --ask app-shells/fzf
XBPSVoid Linuxsudo xbps-install -S fzf
ZypperopenSUSEsudo zypper install fzf

Windows

Pre-built binaries for Windows can be downloaded here. fzf is also available via Chocolatey, Scoop, and Winget:

Package managerCommand
Chocolateychoco install fzf
Scoopscoop install fzf
Wingetwinget install fzf

Known issues and limitations on Windows can be found on the wiki page.

Usage

fzf will launch interactive finder, read the list from STDIN, and write the selected item to STDOUT.

1
find * -type f | fzf > selected

Without STDIN pipe, fzf will use find command to fetch the list of files excluding hidden ones. (You can override the default command with FZF_DEFAULT_COMMAND)

1
vim $(fzf)

💡 A more robust solution would be to use xargs but we’ve presented the above as it’s easier to grasp

1
fzf --print0 | xargs -0 -o vim

💡 fzf also has the ability to turn itself into a different process.

1
fzf --bind 'enter:become(vim {})'

See Turning into a different process for more information.

Using the finder

  • CTRL-K / CTRL-J (or CTRL-P / CTRL-N) to move cursor up and down
  • Enter key to select the item, CTRL-C / CTRL-G / ESC to exit
  • On multi-select mode (-m), TAB and Shift-TAB to mark multiple items
  • Emacs style key bindings
  • Mouse: scroll, click, double-click; shift-click and shift-scroll on multi-select mode

Layout

fzf by default starts in fullscreen mode, but you can make it start below the cursor with --height option.

1
vim $(fzf --height 40%)

Also, check out --reverse and --layout options if you prefer “top-down” layout instead of the default “bottom-up” layout.

1
vim $(fzf --height 40% --reverse)

You can add these options to $FZF_DEFAULT_OPTS so that they’re applied by default. For example,

1
export FZF_DEFAULT_OPTS='--height 40% --layout=reverse --border'

Search syntax

Unless otherwise specified, fzf starts in “extended-search mode” where you can type in multiple search terms delimited by spaces. e.g. ^music .mp3$ sbtrkt !fire

TokenMatch typeDescription
sbtrktfuzzy-matchItems that match sbtrkt
'wildexact-match (quoted)Items that include wild
^musicprefix-exact-matchItems that start with music
.mp3$suffix-exact-matchItems that end with .mp3
!fireinverse-exact-matchItems that do not include fire
!^musicinverse-prefix-exact-matchItems that do not start with music
!.mp3$inverse-suffix-exact-matchItems that do not end with .mp3

If you don’t prefer fuzzy matching and do not wish to “quote” every word, start fzf with -e or --exact option. Note that when --exact is set, '-prefix “unquotes” the term.

A single bar character term acts as an OR operator. For example, the following query matches entries that start with core and end with either go, rb, or py.

1
^core go$ | rb$ | py$

Environment variables

  • FZF_DEFAULT_COMMAND
    • Default command to use when input is tty
    • e.g. export FZF_DEFAULT_COMMAND='fd --type f'
    • ⚠️ This variable is not used by shell extensions due to the slight difference in requirements.

      (e.g. CTRL-T runs $FZF_CTRL_T_COMMAND instead, vim **<tab> runs _fzf_compgen_path(), and cd **<tab> runs _fzf_compgen_dir())

      The available options are described later in this document.

  • FZF_DEFAULT_OPTS
    • Default options
    • e.g. export FZF_DEFAULT_OPTS="--layout=reverse --inline-info"

Options

See the man page (man fzf) for the full list of options.

Fuzzy completion for bash and zsh

Files and directories

Fuzzy completion for files and directories can be triggered if the word before the cursor ends with the trigger sequence, which is by default **.

  • COMMAND [DIRECTORY/][FUZZY_PATTERN]**<TAB>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# Files under the current directory
# - You can select multiple items with TAB key
vim **<TAB>

# Files under parent directory
vim ../**<TAB>

# Files under parent directory that match `fzf`
vim ../fzf**<TAB>

# Files under your home directory
vim ~/**<TAB>


# Directories under current directory (single-selection)
cd **<TAB>

# Directories under ~/github that match `fzf`
cd ~/github/fzf**<TAB>

Process IDs

Fuzzy completion for PIDs is provided for kill command.

1
2
# Can select multiple processes with <TAB> or <Shift-TAB> keys
kill -9 **<TAB>

Host names

For ssh and telnet commands, fuzzy completion for hostnames is provided. The names are extracted from /etc/hosts and ~/.ssh/config.

1
2
ssh **<TAB>
telnet **<TAB>

Environment variables / Aliases

1
2
3
unset **<TAB>
export **<TAB>
unalias **<TAB>

Settings

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# Use ~~ as the trigger sequence instead of the default **
export FZF_COMPLETION_TRIGGER='~~'

# Options to fzf command
export FZF_COMPLETION_OPTS='--border --info=inline'

# Use fd (https://github.com/sharkdp/fd) instead of the default find
# command for listing path candidates.
# - The first argument to the function ($1) is the base path to start traversal
# - See the source code (completion.{bash,zsh}) for the details.
_fzf_compgen_path() {
  fd --hidden --follow --exclude ".git" . "$1"
}

# Use fd to generate the list for directory completion
_fzf_compgen_dir() {
  fd --type d --hidden --follow --exclude ".git" . "$1"
}

# Advanced customization of fzf options via _fzf_comprun function
# - The first argument to the function is the name of the command.
# - You should make sure to pass the rest of the arguments to fzf.
_fzf_comprun() {
  local command=$1
  shift

  case "$command" in
    cd)           fzf --preview 'tree -C {} | head -200'   "$@" ;;
    export|unset) fzf --preview "eval 'echo \$'{}"         "$@" ;;
    ssh)          fzf --preview 'dig {}'                   "$@" ;;
    *)            fzf --preview 'bat -n --color=always {}' "$@" ;;
  esac
}

Supported commands

On bash, fuzzy completion is enabled only for a predefined set of commands (complete | grep _fzf to see the list). But you can enable it for other commands as well by using _fzf_setup_completion helper function.

1
2
3
# usage: _fzf_setup_completion path|dir|var|alias|host COMMANDS...
_fzf_setup_completion path ag git kubectl
_fzf_setup_completion dir tree

Custom fuzzy completion

(Custom completion API is experimental and subject to change)

For a command named “COMMAND”, define _fzf_complete_COMMAND function using _fzf_complete helper.

1
2
3
4
5
6
7
8
9
10
# Custom fuzzy completion for "doge" command
#   e.g. doge **<TAB>
_fzf_complete_doge() {
  _fzf_complete --multi --reverse --prompt="doge> " -- "$@" < <(
    echo very
    echo wow
    echo such
    echo doge
  )
}
  • The arguments before -- are the options to fzf.
  • After --, simply pass the original completion arguments unchanged ("$@").
  • Then, write a set of commands that generates the completion candidates and feed its output to the function using process substitution (< <(...)).

zsh will automatically pick up the function using the naming convention but in bash you have to manually associate the function with the command using the complete command.

1
[ -n "$BASH" ] && complete -F _fzf_complete_doge -o default -o bashdefault doge

If you need to post-process the output from fzf, define _fzf_complete_COMMAND_post as follows.

1
2
3
4
5
6
7
8
9
10
11
_fzf_complete_foo() {
  _fzf_complete --multi --reverse --header-lines=3 -- "$@" < <(
    ls -al
  )
}

_fzf_complete_foo_post() {
  awk '{print $NF}'
}

[ -n "$BASH" ] && complete -F _fzf_complete_foo -o default -o bashdefault foo

Advanced topics

Performance

fzf is fast. Performance should not be a problem in most use cases. However, you might want to be aware of the options that can affect performance.

  • --ansi tells fzf to extract and parse ANSI color codes in the input, and it makes the initial scanning slower. So it’s not recommended that you add it to your $FZF_DEFAULT_OPTS.
  • --nth makes fzf slower because it has to tokenize each line.
  • --with-nth makes fzf slower as fzf has to tokenize and reassemble each line.

Executing external programs

You can set up key bindings for starting external processes without leaving fzf (execute, execute-silent).

1
2
3
# Press F1 to open the file with less without leaving fzf
# Press CTRL-Y to copy the line to clipboard and aborts fzf (requires pbcopy)
fzf --bind 'f1:execute(less -f {}),ctrl-y:execute-silent(echo {} | pbcopy)+abort'

See KEY BINDINGS section of the man page for details.

Turning into a different process

become(...) is similar to execute(...)/execute-silent(...) described above, but instead of executing the command and coming back to fzf on complete, it turns fzf into a new process for the command.

1
fzf --bind 'enter:become(vim {})'

Compared to the seemingly equivalent command substitution vim "$(fzf)", this approach has several advantages:

  • Vim will not open an empty file when you terminate fzf with CTRL-C
  • Vim will not open an empty file when you press ENTER on an empty result
  • Can handle multiple selections even when they have whitespaces

    1
    
    fzf --multi --bind 'enter:become(vim {+})'
    

To be fair, running fzf --print0 | xargs -0 -o vim instead of vim "$(fzf)" resolves all of the issues mentioned. Nonetheless, become(...) still offers additional benefits in different scenarios.

  • You can set up multiple bindings to handle the result in different ways without any wrapping script

    1
    
    fzf --bind 'enter:become(vim {}),ctrl-e:become(emacs {})'
    
    • Previously, you would have to use --expect=ctrl-e and check the first line of the output of fzf
  • You can easily build the subsequent command using the field index expressions of fzf

    1
    2
    3
    
    # Open the file in Vim and go to the line
    git grep --line-number . |
        fzf --delimiter : --nth 3.. --bind 'enter:become(vim {1} +{2})'
    

Reloading the candidate list

By binding reload action to a key or an event, you can make fzf dynamically reload the candidate list. See #1750 for more details.

1. Update the list of processes by pressing CTRL-R

1
2
3
4
ps -ef |
  fzf --bind 'ctrl-r:reload(ps -ef)' \
      --header 'Press CTRL-R to reload' --header-lines=1 \
      --height=50% --layout=reverse

2. Switch between sources by pressing CTRL-D or CTRL-F

1
2
3
FZF_DEFAULT_COMMAND='find . -type f' \
  fzf --bind 'ctrl-d:reload(find . -type d),ctrl-f:reload(eval "$FZF_DEFAULT_COMMAND")' \
      --height=50% --layout=reverse

3. Interactive ripgrep integration

The following example uses fzf as the selector interface for ripgrep. We bound reload action to change event, so every time you type on fzf, the ripgrep process will restart with the updated query string denoted by the placeholder expression {q}. Also, note that we used --disabled option so that fzf doesn’t perform any secondary filtering.

1
2
3
4
5
6
: | rg_prefix='rg --column --line-number --no-heading --color=always --smart-case' \
    fzf --bind 'start:reload:$rg_prefix ""' \
        --bind 'change:reload:$rg_prefix {q} || true' \
        --bind 'enter:become(vim {1} +{2})' \
        --ansi --disabled \
        --height=50% --layout=reverse

If ripgrep doesn’t find any matches, it will exit with a non-zero exit status, and fzf will warn you about it. To suppress the warning message, we added || true to the command, so that it always exits with 0.

See “Using fzf as interactive Ripgrep launcher” for more sophisticated examples.

Preview window

When the --preview option is set, fzf automatically starts an external process with the current line as the argument and shows the result in the split window. Your $SHELL is used to execute the command with $SHELL -c COMMAND. The window can be scrolled using the mouse or custom key bindings.

1
2
# {} is replaced with the single-quoted string of the focused line
fzf --preview 'cat {}'

Preview window supports ANSI colors, so you can use any program that syntax-highlights the content of a file, such as Bat or Highlight:

1
fzf --preview 'bat --color=always {}' --preview-window '~3'

You can customize the size, position, and border of the preview window using --preview-window option, and the foreground and background color of it with --color option. For example,

1
2
3
4
fzf --height 40% --layout reverse --info inline --border \
    --preview 'file {}' --preview-window up,1,border-horizontal \
    --bind 'ctrl-/:change-preview-window(50%|hidden|)' \
    --color 'fg:#bbccdd,fg+:#ddeeff,bg:#334455,preview-bg:#223344,border:#778899'

See the man page (man fzf) for the full list of options.

More advanced examples can be found here.


Since fzf is a general-purpose text filter rather than a file finder, it is not a good idea to add --preview option to your $FZF_DEFAULT_OPTS.

1
2
3
4
5
6
7
8
9
# *********************
# ** DO NOT DO THIS! **
# *********************
export FZF_DEFAULT_OPTS='--preview "bat --style=numbers --color=always --line-range :500 {}"'

# bat doesn't work with any input other than the list of files
ps -ef | fzf
seq 100 | fzf
history | fzf

Tips

Respecting .gitignore

You can use fd, ripgrep, or the silver searcher instead of the default find command to traverse the file system while respecting .gitignore.

1
2
3
4
5
6
7
8
9
10
11
# Feed the output of fd into fzf
fd --type f --strip-cwd-prefix | fzf

# Setting fd as the default source for fzf
export FZF_DEFAULT_COMMAND='fd --type f --strip-cwd-prefix'

# Now fzf (w/o pipe) will use fd instead of find
fzf

# To apply the command to CTRL-T as well
export FZF_CTRL_T_COMMAND="$FZF_DEFAULT_COMMAND"

If you want the command to follow symbolic links and don’t want it to exclude hidden files, use the following command:

1
export FZF_DEFAULT_COMMAND='fd --type f --strip-cwd-prefix --hidden --follow --exclude .git'

Fish shell

CTRL-T key binding of fish, unlike those of bash and zsh, will use the last token on the command-line as the root directory for the recursive search. For instance, hitting CTRL-T at the end of the following command-line

1
ls /var/

will list all files and directories under /var/.

When using a custom FZF_CTRL_T_COMMAND, use the unexpanded $dir variable to make use of this feature. $dir defaults to . when the last token is not a valid directory. Example:

1
set -g FZF_CTRL_T_COMMAND "command find -L \$dir -type f 2> /dev/null | sed '1d; s#^\./##'"

This post is licensed under CC BY 4.0 by the author.

Comments powered by Disqus.