Skip to content

Instantly share code, notes, and snippets.

@piranha
Last active February 18, 2025 09:30
Show Gist options
  • Save piranha/dc22bee19df8c634178ff7cc3043abba to your computer and use it in GitHub Desktop.
Save piranha/dc22bee19df8c634178ff7cc3043abba to your computer and use it in GitHub Desktop.
git branch checkout/delete via fzf
#!/bin/sh
set -eo errexit
sep=' '
# NOTE: $1 should not intersect with real branch names
case "$1" in
--LIST)
refname='%(refname:short)'
sha='%(color:yellow)%(objectname:short)%(color:reset)'
date='%(color:green)(%(creatordate:iso8601))%(color:reset)'
author='%(color:bold blue)<%(authorname)>%(color:reset)'
cur='%(if)%(HEAD)%(then)%(color:bold cyan) <- HEAD%(color:reset)%(end)'
upstream='%(if)%(upstream)%(then)%(color:bold red)%(upstream:short)%(color:reset), %(end)'
branch='%(color:bold green)%(refname:short)%(color:reset)'
git for-each-ref refs/heads --sort=-committerdate --color=always \
--format="$refname$sep$sha - $date $author %(subject) ($upstream$branch)$cur"
exit $?
;;
*)
if [ "$(git rev-parse --verify "$1" 2>/dev/null)" ]; then
exec git checkout "$1"
fi
fzf -1 --ansi --no-preview --reverse --query="$1" \
--delimiter="$sep" --with-nth=2 \
--height '~50%' \
--header 'Select a branch; press Alt-Backspace to delete a branch' \
--bind "start:reload:$0 --LIST" \
--bind "enter:become(git switch '{1}')" \
--bind "alt-backspace:execute-silent(git branch -D '{1}')+reload($0 --LIST)"
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment