Skip to content

Instantly share code, notes, and snippets.

@r4mbo7
Created September 17, 2026 14:16
Show Gist options
  • Select an option

  • Save r4mbo7/2ef5f53a0d16e3704599db9edffeb2cc to your computer and use it in GitHub Desktop.

Select an option

Save r4mbo7/2ef5f53a0d16e3704599db9edffeb2cc to your computer and use it in GitHub Desktop.
gw - jump between git worktrees in zsh, with tab completion
# gw - jump between git worktrees in zsh, with tab completion.
#
# gw <fragment> cd into the first worktree whose path matches <fragment>
# gw cd into the main checkout (always the first entry listed)
# gw <Tab> list worktrees by directory name, annotated with their branch
#
# Add to ~/.zshrc after compinit runs (e.g. after sourcing oh-my-zsh).
gw() {
local p
p=$(git worktree list --porcelain | awk '/^worktree /{print $2}' | grep -i -- "${1:-}" | head -1)
[[ -n $p ]] && cd "$p" || echo "no worktree matching '${1:-}'" >&2
}
_gw() {
local -a entries
local line wt br
git rev-parse --git-dir &>/dev/null || return 1
while IFS= read -r line; do
case $line in
"worktree "*) wt=${line#worktree } ;;
"branch "*) br=${line#branch refs/heads/} ;;
"detached") br="detached" ;;
"") [[ -n $wt ]] && entries+=("${wt:t}:${br:-?}"); wt= ; br= ;;
esac
done < <(git worktree list --porcelain)
[[ -n $wt ]] && entries+=("${wt:t}:${br:-?}")
_describe -t worktrees 'worktree' entries
}
compdef _gw gw
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment