[zsh+fzf] Find That Vaguely Remembered “Command” or “Directory” with Fuzzy Search
Back to TopTo reach a broader audience, this article has been translated from Japanese.
You can find the original version here.
This is the first-day article of the Mamezou Developer Site Advent Calendar 2026.
Introduction
#When I first started using a MacBook after beginning my career, I barely used the terminal. Checking where I was and what existed in that directory, while repeatedly running cd and ls, was simply too much trouble.
The same was true for rerunning commands. I only wanted to run a command I had used before, but even repeatedly pressing the arrow keys would not easily get me there.
What changed this situation was fzf.
After introducing it, terminal operations became more “direct.” I can achieve goals such as “I want to go to that directory with that name” or “I want to run that command from earlier again” almost instantly.
This article introduces the configuration for doing so.
What It Looks Like When Complete
#First, take a look at what you will be able to do after configuration.
Ctrl+R: Fuzzy-search and run past commands
#Even if you only vaguely remember a keyword, you can recall commands without navigating with the arrow keys. In the GIF below, simply typing conti narrows down and recalls claude --continue from the command history.
Ctrl+O: Fuzzy-search and jump to previously visited directories
#Even if you do not remember the path, you can get there without the twists and turns of cd and ls as long as you vaguely remember the name. In the GIF below, simply typing claude jumps to the previously visited ~/.claude directory.
Prerequisites
#This article has been tested in the following environment.
| Item | Version |
|---|---|
| OS | macOS 27.2.1 |
| Shell | zsh 5.9 |
| Package manager | Homebrew 7.0.17 (already installed) |
Since Catalina (10.15), macOS has used zsh as its default shell (official Apple support page). You can check your currently used shell and its version with the following command.
echo $ZSH_VERSION
When run in zsh, it displays a version such as 5.9. If nothing is displayed, you may be running a shell other than zsh, such as bash.
Overview of the Configuration
#The setup consists of the following three steps.
| Step | What to do | What you get |
|---|---|---|
| 1 | Install fzf | A fuzzy-search UI |
| 2 | Enable fzf shell integration | Ctrl+R / Ctrl+T / Alt+C |
| 3 | Write a function connecting zsh cdr and fzf |
Ctrl+O (jump to previously visited directories) |
Ctrl+R becomes available with step 2 alone. However, fzf's standard Alt+C searches only “under the current directory.” To search across “previously visited directories,” you need to combine it with zsh's cdr in step 3.
Step 1: Install fzf
#Install it with Homebrew.
brew install fzf
Step 2: Enable fzf Shell Integration
#Add the following to ~/.zshrc.
# fzf shell integration (Ctrl+R: history search, Ctrl+T: file search, Alt+C: directory navigation)
export FZF_CTRL_R_OPTS="--reverse"
source <(fzf --zsh)
The meaning of each line is as follows.
export FZF_CTRL_R_OPTS="--reverse"
This specifies options passed to fzf when starting history search with Ctrl+R. Adding --reverse places the input field at the top and the candidates below it. By default, fzf displays the input field at the bottom, so this reverses it to make it easier to read naturally from top to bottom. This is a matter of preference, so you can omit it if you do not need it.
source <(fzf --zsh)
fzf --zsh is a command that outputs a script for integrating fzf with zsh (definitions for key bindings and completion). Loading its output into the current shell with source enables the following key bindings. The official release notes recommend eval "$(fzf --zsh)", and either option is fine.
| Key binding | Function |
|---|---|
| Ctrl+R | Fuzzy-search command history |
| Ctrl+T | Fuzzy-search files under the current directory |
| Alt+C | Move to a directory under the current directory |
The --zsh flag was added in fzf v0.48.0. In earlier versions, fzf --zsh itself cannot be used. In that case, you need to load individual scripts such as ~/.fzf.zsh or key-bindings.zsh + completion.zsh.
In the macOS terminal, the Option key is not treated as Alt (the Meta key) by default. Pressing Option+C only enters ç; fzf does not start. In Terminal.app, enable “Use Option as Meta key” under “Settings > Profiles > Keyboard.” In iTerm2, set the Option key to Esc+ under “Settings > Profiles > Keys.”
For details on each option and key binding, refer to the official fzf documentation.
- fzf README - Setting up shell integration
- fzf README - Key bindings for command-line (
FZF_CTRL_R_OPTS, etc.)
Step 3: Search Directory History with fzf (cdr + Ctrl+O)
#Add the following to ~/.zshrc. The configuration for enabling cdr and integrating it with fzf was based on zshでfzfを使ってコマンドと移動履歴を検索する.
# --- First half: record recently visited directories (cdr) ---
# cdr is included with zsh 4.3.11+. It is always available in macOS zsh.
autoload -Uz chpwd_recent_dirs cdr add-zsh-hook
add-zsh-hook chpwd chpwd_recent_dirs
zstyle ':chpwd:*' recent-dirs-max 1000
zstyle ':chpwd:*' recent-dirs-file "${XDG_CACHE_HOME:-$HOME/.cache}/chpwd-recent-dirs"
# --- Second half: narrow down history with fzf and cd (Ctrl+O) ---
function fzf-cdr() {
# cdr -l outputs "number␣␣abbreviated-path-with-~", so remove the leading number and extract only the path
local selected
selected=$(cdr -l | sed -e 's/^[[:digit:]]*[[:blank:]]*//' | fzf --reverse --query "$LBUFFER") || return
if [[ -z $selected ]]; then
zle reset-prompt
return
fi
# Expand the leading ~ to $HOME and quote it so paths containing spaces do not break
local dir=${selected/#\~/$HOME}
BUFFER="cd -- ${(q)dir}"
zle accept-line
}
zle -N fzf-cdr
bindkey '^o' fzf-cdr
As the comments in the code indicate, let us look at the first and second halves separately.
First Half: Record Recently Visited Directories (cdr)
#cdr is a standard zsh function for returning to working directories you have visited in the past. History is recorded automatically and listed in order from most recent.
autoload -Uz chpwd_recent_dirs cdr add-zsh-hook
Registers the required functions for lazy loading (they are loaded when used). -U suppresses alias expansion. It prevents aliases defined by the user from being incorporated into the function body when loading functions. -z loads in zsh style. It forces zsh style regardless of the environment's KSH_AUTOLOAD setting.
add-zsh-hook chpwd chpwd_recent_dirs
Associates chpwd_recent_dirs with the chpwd hook, which fires when changing directories. This automatically records the destination in history every time you run cd. This is the core mechanism that accumulates history.
zstyle ':chpwd:*' recent-dirs-max 1000
This is the number of history entries to retain. The default is 20 entries, so this increases it to 1000.
zstyle ':chpwd:*' recent-dirs-file ...
This is the file in which history is stored. The default is ~/.chpwd-recent-dirs. To avoid cluttering the home directory, it is placed under ~/.cache/. If XDG_CACHE_HOME is already set, it takes priority.
Here, this is intentionally not wrapped in a zsh version check. This is because cdr is always available in the standard macOS zsh (5.x) assumed by this article. If you also need to target older zsh versions, you can wrap it with autoload -Uz is-at-least; if is-at-least 4.3.11; then ... fi.
Second Half: Narrow Down History with fzf and cd (Ctrl+O)
#Let us go through the fzf-cdr function step by step.
1. Pass history to fzf and select one entry
selected=$(cdr -l | sed -e 's/^[[:digit:]]*[[:blank:]]*//' | fzf --reverse --query "$LBUFFER") || return
This single line is the core of the process.
- Use
cdr -lto list history in the form “number + directory” (example:1 ~/work/project) - Use
sedto remove the number and spaces at the beginning of each line, leaving only the directory path - Pass the remaining list of paths to
fzffor fuzzy searching
--query "$LBUFFER" passes the text currently being entered on the command line to fzf as the initial search query. The selected path is stored in selected. If you exit fzf with Esc, || return exits without doing anything.
The local selected declaration and the selected=$(...) assignment are intentionally split into two lines. If you combine them as local selected=$(...), the exit status becomes the success status (0) of local itself. As a result, the nonzero status when fzf is canceled cannot be detected, and || return will not work.
2. If nothing is selected, redraw the prompt and finish
If selected is empty, it only redraws the prompt with zle reset-prompt and returns.
3. Build and execute a command to cd to the selected path
local dir=${selected/#\~/$HOME}
BUFFER="cd -- ${(q)dir}"
zle accept-line
The output of cdr -l uses the abbreviated ~ form. However, a ~ stored in a variable is not expanded automatically. Therefore, ${selected/#\~/$HOME} replaces the leading ~ with $HOME, turning it into the actual path.
${(q)dir} quotes the path so it can be passed safely as a single argument even if it contains spaces or symbols. The -- in cd -- is a separator that prevents directories with names beginning with - from being mistaken for options.
Finally, zle accept-line executes the constructed BUFFER (command line) as if Enter had been pressed. The executed command is also retained in command history.
Simply writing BUFFER="cd $selected" causes cd to fail for paths containing spaces, such as ~/space dir/sub. This is because the argument to cd is split into ~/space and dir/sub. macOS has many paths containing spaces, including Mobile Documents in iCloud Drive, so this can cause real issues. As shown above, expanding ~ to $HOME first and then quoting it with ${(q)dir} allows cd to work correctly even with paths containing spaces.
4. Register it as a widget and assign it to Ctrl+O
Register the created function as a ZLE widget with zle -N fzf-cdr, then assign it to Ctrl+O with bindkey '^o' fzf-cdr.
The specifications for cdr / zstyle / autoload discussed so far are documented in the following sections of the official zsh manual.
- User Contributions - Remembering Recent Directories: each setting including
cdr, and the official setup procedure (the Installation section) - Shell Builtin Commands: meanings of the
-U/-zflags forautoload
Apply the Configuration and Verify It Works
#Apply the configuration.
source ~/.zshrc
After applying it, try the following.
| Key binding | What happens |
|---|---|
| Ctrl+R | The fzf filtering interface starts, allowing you to search command history |
| Ctrl+O | Previously visited directories can be filtered with fzf and jumped to |
Candidates for Ctrl+O begin accumulating from directories you cd into after applying the configuration. Immediately after configuration, there will be very few candidates, but they will naturally increase as you work normally.
Summary
#This article introduced a configuration that combines zsh and fzf to reach vaguely remembered commands and directories.
- Ctrl+R: Simply enabling fzf shell integration lets you fuzzy-search command history.
- Ctrl+O: By accumulating navigation history with zsh's
cdrand writing a function to filter it with fzf, you can jump to previously visited directories.
Both require adding only a few to a dozen or so lines to ~/.zshrc. If you are tired of going back and forth between cd and ls, or repeatedly pressing arrow keys, give it a try.
References
#- junegunn/fzf - GitHub
- zshでfzfを使ってコマンドと移動履歴を検索する - Zenn (used as a reference for cdr + fzf configuration)
- zsh: User Contributions - Remembering Recent Directories (official documentation for
cdr/zstyle)


