Skip to content

Instantly share code, notes, and snippets.

@sushichan044
Last active June 5, 2025 15:24
Show Gist options
  • Select an option

  • Save sushichan044/9be39a04f4c18eab43429ca6455ccd78 to your computer and use it in GitHub Desktop.

Select an option

Save sushichan044/9be39a04f4c18eab43429ca6455ccd78 to your computer and use it in GitHub Desktop.
Interactively select a git worktree within the current directory and its subdirectories using fzf, and then easily cd into it.
#!/bin/zsh
# fzf-based git worktree selector
# Inspired by:
# - https://www.mizdra.net/entry/2024/10/19/172323 (git branch selection patterns)
#
# Usage:
# - Direct: fzf-worktree
# - Keybind: Ctrl+N
#
# Features:
# - Lists all git worktrees with enhanced preview
# - Shows git log in preview pane
# - Works both from command line and as ZLE widget
# Prerequisites:
# - git
# - fzf
# - zsh
function fzf-worktree() {
# Format of `git worktree list`: path commit [branch]
local selected_worktree=$(git worktree list | fzf \
--prompt="worktrees > " \
--header="Select a worktree to cd into" \
--preview="echo 'πŸ“¦ Branch:' && git -C {1} branch --show-current && echo '' && echo 'πŸ“ Changed files:' && git -C {1} status --porcelain | head -10 && echo '' && echo 'πŸ“š Recent commits:' && git -C {1} log --oneline --decorate -10" \
--preview-window="right:40%" \
--reverse \
--border \
--ansi)
if [ $? -ne 0 ]; then
return 0
fi
if [ -n "$selected_worktree" ]; then
local selected_path=${${(s: :)selected_worktree}[1]}
if [ -d "$selected_path" ]; then
if zle; then
# Called from ZLE (keyboard shortcut)
BUFFER="cd ${selected_path}"
zle accept-line
else
# Called directly from command line
cd "$selected_path"
fi
else
echo "Directory not found: $selected_path"
return 1
fi
fi
# Only clear screen if ZLE is active
if zle; then
zle clear-screen
fi
}
zle -N fzf-worktree
bindkey '^n' fzf-worktree
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment