Skip to content
Hands-on IT IT Drills

Day 7: fzf everywhere

Goal: Search every list in the terminal (files, directories, history, branches, processes, contexts) with a fuzzy finder and build your own pickers. · Duration: approx. 75 min · Prerequisite: Day 6

Briefing

  • fzf reads lines from stdin, you filter interactively, the selection goes to stdout. That’s all there is to it.
  • That’s why it fits in between anywhere: liste | fzf | befehl.
  • It ships with three key bindings (⌃T, ⌃R, ⌥C) and the **<Tab> completion.
  • As the source you use fd (Day 6), for the preview bat and eza.
  • Everything goes into a module file: ~/term-lab/config/zsh/fzf.zsh.
  fd / git / ps / kubectl  ──stdin──▶  fzf  ──stdout──▶  $EDITOR / git switch / kill
          source                    selection                    action

Drill 1: fzf as a filter in the pipe

cd ~/term-lab/projekt
fd -t f | fzf

Type cart, select with ⌃J/⌃K (or the arrow keys), confirm with Enter. Expected:

internal/cart/cart.go

The selection lands on stdout. So you can pass it on:

bat "$(fd -e yaml | fzf)"

The search syntax is more than “letters in order”. With --filter you test it without the UI:

fd -t f -H -E .git > /tmp/lab-files.txt
for q in "cmdgo" "'cart" "^config" ".yaml$" "yaml !deploy" "go$ | py$"; do
  printf '%-14s -> ' "$q"; fzf --filter "$q" < /tmp/lab-files.txt | xargs
done

Expected:

cmdgo          -> cmd/shop/main.go
'cart          -> internal/cart/cart.go
^config        -> config/app.json config/app.yaml
.yaml$         -> config/app.yaml deploy/k8s/deployment.yaml
yaml !deploy   -> config/app.yaml
go$ | py$      -> cmd/shop/main.go scripts/report.py internal/cart/cart.go
Pattern Meaning Mnemonic
cmdgo fuzzy: letters in this order default
'cart exactly this text apostrophe = literal
^config starts with like regex ^
.yaml$ ends with like regex $
!deploy doesn’t contain ! = not
a b AND space = and

You write OR with a pipe character between spaces: go$ | py$.

Save your progress? Sign up for free

Drill 2: Configuration and ⌃T

fzf brings the key bindings itself (fzf --zsh, since version 0.48). Add fd as the source and a preview with bat:

cat > ~/term-lab/config/zsh/fzf.zsh <<'EOF'
# fzf.zsh – fzf everywhere (Day 7)
(( $+commands[fzf] )) || return 0

# Key bindings ⌃T, ⌃R, ⌥C and **<Tab> completion (fzf >= 0.48)
source <(fzf --zsh)

# Sources: fd instead of find – fast, respects .gitignore
export FZF_DEFAULT_COMMAND='fd --type f --hidden --exclude .git'
export FZF_DEFAULT_OPTS='--height 40% --layout reverse --border --info inline-right'
export FZF_CTRL_T_COMMAND=$FZF_DEFAULT_COMMAND
export FZF_CTRL_T_OPTS="--preview 'bat --color=always --style=numbers \
--line-range :100 {}' --bind 'ctrl-/:toggle-preview'"
export FZF_ALT_C_COMMAND='fd --type d --hidden --exclude .git'
export FZF_ALT_C_OPTS="--preview 'eza --tree --level=2 --color=always {}'"
export FZF_CTRL_R_OPTS="--preview 'echo {2..}' --preview-window down:3:wrap:hidden \
--bind '?:toggle-preview'"

# **<Tab> uses fd as well
_fzf_compgen_path() { fd --hidden --exclude .git . "$1"; }
_fzf_compgen_dir()  { fd --type d --hidden --exclude .git . "$1"; }
EOF
reload
bindkey | rg fzf

Expected:

"^I" fzf-completion
"^R" fzf-history-widget
"^T" fzf-file-widget
"^[c" fzf-cd-widget

Now type bat (with a space), then ⌃T, then deplo:

[lab] projekt % bat
╭───────────────────────────────────────────────────────────────────────╮
│ > deplo                    1/10 (0) ╭────────────────────────────────╮ │
│ ─────────────────────────────────── │    1 apiVersion: apps/v1       │ │
│ ▌ deploy/k8s/deployment.yaml        │    2 kind: Deployment          │ │
│                                     │    3 metadata:                 │ │
│                                     │    4   name: shop              │ │

Enter inserts the path at the cursor position:

[lab] projekt % bat deploy/k8s/deployment.yaml

⌃/ hides and shows the preview. With Tab you mark several files, and all of them then land in the line.

Save your progress? Sign up for free

Drill 3: ⌃R for the history, ⌥C for directories

⌃R searches the history fuzzily. Type yq:

╭──────────────────────────────────────────────────────────────────────────╮
│ > yq                                                                 4/5 │
│ ──────────────────────────────────────────────────────────────────────── │
│ ▌ 50  a=$(jq .replicas config/app.json); b=$(yq .spec.replicas deploy/k8 │
│   38  yq .database.host config/app.yaml                                  │
  • Enter puts the command into the line; it only runs with the next Enter.
  • ⌃R in the picker toggles between “by relevance” and “chronological”.
  • ? shows long commands wrapped in the preview (our FZF_CTRL_R_OPTS).

Tip: Day 4 puts atuin on ⌥R. If you put it on ⌃R after all, the file loaded last wins. Decide on one tool per key and check with bindkey '^R'.

⌥C jumps into a subdirectory via fzf. That needs “Option as Meta” from Day 1. Type k8s:

│ > k8s                     1/9 ╭──────────────────────────────╮
│ ───────────────────────────── │ deploy/k8s                   │
│ ▌ deploy/k8s/                 │ └── deployment.yaml          │

Expected after Enter:

[lab] projekt % builtin cd -- /Users/du/term-lab/projekt/deploy/k8s
[lab] k8s %

If a ç appears in the terminal instead of fzf, ⌥ isn’t sending Meta yet (Day 1). Fallback: Esc, then c.

Save your progress? Sign up for free

Drill 4: **<Tab> – fzf in every command

Two asterisks and Tab open fzf for the current argument. The command in front determines what is offered:

cd ~/term-lab/projekt
bat cart**

Press Tab right after the asterisks:

│ > cart                                                     2/19 (0) │
│ ─────────────────────────────────────────────────────────────────── │
│ ▌ ./internal/cart/cart.go                                           │
│ ▌ ./internal/cart/                                                  │

Expected after Enter:

[lab] projekt % bat ./internal/cart/cart.go

Special cases fzf knows out of the box:

Input List Mnemonic
cd **<Tab> directories only cd wants folders
kill **<Tab> processes (ps) kill wants PIDs
ssh **<Tab> hosts from ~/.ssh/config and known_hosts ssh wants hosts
export **<Tab>, unset **<Tab> environment variables variables

Kill a process without hunting for the PID:

sleep 600 &
kill **

Press Tab, type sleep 600:

│ > sleep 600                                                142/536 (0) │
│   USER               PID  PPID STARTED      TIME COMMAND               │
│ ▌ du                3401 89549  8:44am   0:00.00 sleep 600             │

Expected after pressing Enter twice:

[lab] projekt % kill 3401
[1]  + terminated  sleep 600

Save your progress? Sign up for free

Drill 5: Your own pickers – Git branch and processes

The pattern is always the same: generate a list, fzf, pass the result to a command. Canceling (Esc) returns exit code 130, hence || return 1.

cat >> ~/term-lab/config/zsh/fzf.zsh <<'EOF'

# --- Own pickers -----------------------------------------------------------

# fbr – pick a Git branch and switch to it (local and remote)
fbr() {
  local br
  br=$(git branch --all --sort=-committerdate --format='%(refname:short)' |
    grep -v HEAD |
    fzf --prompt='branch> ' --preview 'git log --oneline --color=always -10 {}') \
    || return 1
  git switch "${br#origin/}"
}

# fkill – pick process(es) (Tab for multi-select) and kill them
fkill() {
  local pids
  pids=$(ps -u "$USER" -o pid=,etime=,command= |
    fzf --multi --prompt='kill> ' --accept-nth=1) || return 1
  print -r -- "kill ${1:--TERM} ${(f)pids}"
  kill "${1:--TERM}" ${(f)pids}
}
EOF
reload
fbr

Type rab:

│ branch> rab              1/2 ╭──────────────────────────────────────╮ │
│ ──────────────────────────── │ 375fbf7 feat: Rabatt-Schalter        │ │
│ ▌ feature/rabatt             │ 2e4e6aa chore: Config, Manifeste, Re │ │
│                              │ a57983c feat: Warenkorb und HTTP-Ser │ │

Expected after Enter:

Zu Branch 'feature/rabatt' gewechselt

Go back with git switch main. ${br#origin/} cuts off the remote prefix. That way git switch automatically creates a local tracking branch for a remote branch.

Now kill two processes at once:

sleep 701 & sleep 702 &
fkill

Type sleep 70, mark both lines with Tab, then Enter:

│ kill> sleep 70                                                89/380 (2) │
│ ▌┃ 5652       00:00 sleep 701                                            │
│ ▌┃ 5654       00:00 sleep 702                                            │

Expected (shortened):

kill -TERM 5652 5654
[1]  - terminated  sleep 701
[2]  + terminated  sleep 702

--accept-nth=1 returns only the first column (PID). That has existed since fzf 0.60. Older versions need | awk '{print $1}'. fkill -9 sends SIGKILL, only as a last resort.

Save your progress? Sign up for free

Drill 6: Kubernetes context via picker

You don’t need a cluster for this. A lab kubeconfig with three contexts is enough; your real ~/.kube/config stays untouched:

export KUBECONFIG=~/term-lab/kube/config
mkdir -p ~/term-lab/kube
kubectl config set-cluster lab --server=https://127.0.0.1:6443 >/dev/null
for c in lab-dev lab-staging lab-prod; do
  kubectl config set-context $c --cluster=lab --user=lab --namespace=webshop
done
kubectl config use-context lab-dev

Expected:

Context "lab-dev" created.
Context "lab-staging" created.
Context "lab-prod" created.
Switched to context "lab-dev".

The picker shows the active context in the header:

cat >> ~/term-lab/config/zsh/fzf.zsh <<'EOF'

# fkctx – pick a Kubernetes context (shows the active context in the header)
fkctx() {
  local ctx
  ctx=$(kubectl config get-contexts -o name |
    fzf --prompt='context> ' \
      --header "aktiv: $(kubectl config current-context 2>/dev/null)") \
    || return 1
  kubectl config use-context "$ctx"
}
EOF
reload
export KUBECONFIG=~/term-lab/kube/config
fkctx

Type prod:

│ context> prod                                                        1/3 │
│ ──────────────────────────────────────────────────────────────────────── │
│   aktiv: lab-dev                                                         │
│ ▌ lab-prod                                                               │

Expected after Enter:

Switched to context "lab-prod".

kubectx without arguments does the same as soon as fzf is installed. kubens picks the namespace the same way. You need your own picker when you want more, for example a confirmation for *prod* (Challenge).

Save your progress? Sign up for free

Drill 7: frg – search, pick, open at the line

rg finds, fzf picks, the editor jumps to the matching line. --delimiter : splits datei:zeile:text into fields, the preview scrolls to the line with +{2}/2:

cat >> ~/term-lab/config/zsh/fzf.zsh <<'EOF'

# frg – search text with rg, pick a match, open it in the editor at the line
frg() {
  [[ -n $1 ]] || { print -u2 "usage: frg <muster>"; return 2; }
  local hit
  hit=$(rg --line-number --no-heading --color=always -- "$1" |
    fzf --ansi --delimiter : --prompt='rg> ' --height 80% \
      --preview 'bat --color=always --highlight-line {2} {1}' \
      --preview-window 'down,60%,+{2}/2') || return 1
  ${EDITOR:-vi} "+${${hit#*:}%%:*}" "${hit%%:*}"
}
EOF
reload
EDITOR=echo frg TODO

Type rabatt:

│ rg> rabatt                                                          1/3  │
│ ──────────────────────────────────────────────────────────────────────── │
│ ▌ internal/cart/cart.go:16:       // TODO: Rabatte berücksichtigen       │
│ ╭──────────────────────────────────────────────────────────────────────╮ │
│ │   10 │ // Total summiert alle Positionen.                             │ │

Expected after Enter (EDITOR=echo only shows what the editor would get):

+16 internal/cart/cart.go

Without EDITOR=echo, Neovim opens directly at line 16. From Day 11 on, $EDITOR is the lab wrapper nv, and frg uses it automatically. ${hit%%:*} is everything before the first colon, ${${hit#*:}%%:*} the field in between.

Save your progress? Sign up for free

Drill 8: fzf-tab – every completion as a fuzzy list

**<Tab> is good, but zsh knows many more completions: Git branches, kubectl resources, options. The fzf-tab plugin puts fzf over every Tab completion. It’s a Git repo, not a Homebrew package:

git clone -q --depth 1 https://github.com/Aloxaf/fzf-tab \
  ~/term-lab/plugins/fzf-tab
cat >> ~/term-lab/config/zsh/fzf.zsh <<'EOF'

# --- fzf-tab (optional): replace the zsh completion menu with fzf ------------
# Installation: git clone --depth 1 https://github.com/Aloxaf/fzf-tab \
#   "$LAB/plugins/fzf-tab"   – must be loaded AFTER compinit.
if [[ -r $LAB/plugins/fzf-tab/fzf-tab.plugin.zsh ]]; then
  source "$LAB/plugins/fzf-tab/fzf-tab.plugin.zsh"
  zstyle ':completion:*' menu no
  zstyle ':completion:*:descriptions' format '[%d]'
  zstyle ':fzf-tab:complete:cd:*' fzf-preview 'eza -1 --color=always $realpath'
  zstyle ':fzf-tab:*' switch-group '<' '>'
fi
EOF
reload
bindkey '^I'

Expected:

"^I" fzf-tab-complete

Type git switch and Tab:

[lab] projekt % git switch
>
  2/2 (0) ──────────────────────────────────────────────────────────
▌ feature/rabatt
▌ main

cd plus Tab shows the folders with an eza preview. **<Tab> still works.

The finished fzf.zsh with all pickers (and the solution to the challenge) is at $BUCH/zsh/fzf.zsh.

Warning: fzf-tab must load after compinit, but before plugins that wrap widgets (zsh-autosuggestions, fast-syntax-highlighting). The lab .zshrc loads config/zsh/*.zsh alphabetically after compinit. That fits.

Save your progress? Sign up for free

Shortcut table

Key Effect Mnemonic
⌃T pick file(s) and insert them into the line Take file
⌃R search the history fuzzily Reverse search
⌥C change into a subdirectory Change dir
** Tab fzf for the current argument two stars = everything
⌃J / ⌃K down / up in the list vim j/k with ⌃
Tab / ⇧Tab mark entry / remove mark pick several
⌃/ preview on/off (our config) slash = split the window
Esc, ⌃C cancel (exit code 130) get out

Checkpoint

cd ~/term-lab/projekt
c() { eval "$2" >/dev/null 2>&1 && echo "✔ $1" || echo "✘ $1"; }
c "⌃T gebunden"        '[[ $(bindkey "^T") == *fzf-file-widget ]]'
c "⌃R gebunden"        '[[ $(bindkey "^R") == *fzf-history-widget ]]'
c "⌥C gebunden"        '[[ $(bindkey "^[c") == *fzf-cd-widget ]]'
c "Quelle ist fd"      '[[ $FZF_DEFAULT_COMMAND == fd* ]]'
c "Vorschau mit bat"   '[[ $FZF_CTRL_T_OPTS == *bat* ]]'
c "Picker vorhanden"   'whence fbr fkill fkctx frg'
c "Suchsyntax"         '[[ $(fd -e go | fzf --filter "^int") == */cart.go ]]'
c "Lab-kubeconfig"     '[[ $KUBECONFIG == *term-lab/kube/config ]]'
c "fzf-tab (optional)" '[[ $(bindkey "^I") == *fzf-tab-complete ]]'

Expected: all ✔. If Lab-kubeconfig shows a ✘, this shell is just missing the export KUBECONFIG=~/term-lab/kube/config from Drill 6.

Challenge

Extend fkctx: if the selected context contains prod, the function asks before switching. On “n” the old context stays active and the exit code is 1.

Hint: Pattern from please (Day 5): read -q "?Frage ".

Solution

cat >> ~/term-lab/config/zsh/fzf.zsh <<'EOF'

# fkctx with confirmation for production (overrides the version from Drill 6)
fkctx() {
  local ctx
  ctx=$(kubectl config get-contexts -o name |
    fzf --prompt='context> ' \
      --header "aktiv: $(kubectl config current-context 2>/dev/null)") \
    || return 1
  if [[ $ctx == *prod* ]]; then
    read -q "?Wirklich nach $ctx wechseln? [y/N] " || { print; return 1; }
    print
  fi
  kubectl config use-context "$ctx"
}
EOF
reload
export KUBECONFIG=~/term-lab/kube/config
kubectl config use-context lab-dev
fkctx

Type prod, Enter, then n:

Switched to context "lab-dev".
Wirklich nach lab-prod wechseln? [y/N] n
echo "rc=$?"; kubectl config current-context

Expected:

rc=1
lab-dev

Save your progress? Sign up for free

Enterprise Note

  • Always build pickers for dangerous targets (prod contexts, kill, git push --force) with a confirmation or a colored header. A typo in the fuzzy match happens quickly.
  • Set KUBECONFIG per project (direnv, Day 14) instead of maintaining one huge ~/.kube/config with all clients.
  • fzf runs preview commands in a shell. Always let fzf insert file names from third-party repos via the {} placeholders; fzf quotes them. Never assemble them into strings yourself.
  • The ⌃R history often contains tokens from curl -H "Authorization: …". Set HIST_IGNORE_SPACE (Day 4) and type such commands with a leading space.
  • fzf-tab and other plugins are third-party code in your shell: pin them to a commit and apply updates deliberately (Day 13).