Skip to content

Instantly share code, notes, and snippets.

@FATESAIKOU
Created July 12, 2026 00:49
Show Gist options
  • Select an option

  • Save FATESAIKOU/2d9baeb2a8197caaa3456cc189c48ed0 to your computer and use it in GitHub Desktop.

Select an option

Save FATESAIKOU/2d9baeb2a8197caaa3456cc189c48ed0 to your computer and use it in GitHub Desktop.
git branch selector
#!/usr/bin/env bash
set -euo pipefail
INITIAL_QUERY="${1:-}"
REMOTES=$(git remote 2>/dev/null | paste -sd ' ' -)
[ -z "$REMOTES" ] && REMOTES="(none)"
CURRENT_BRANCH=$(git branch --show-current 2>/dev/null || echo "???")
HEADER="Pattern: ${INITIAL_QUERY:-<type to search>} | Remotes: ${REMOTES} | Current: ${CURRENT_BRANCH}"
BRANCHES=$( {
git branch --format='%(refname:short)'
git branch -r --format='%(refname:short)'
} | sort -u )
SELECTED=$(echo "$BRANCHES" | fzf \
--sync \
--header="$HEADER" \
--header-first \
--query="$INITIAL_QUERY" \
--preview='git log --oneline -30 {} 2>/dev/null || echo "(no commits)"' \
--preview-window='right:50%:wrap:border-rounded' \
--preview-label=' Commit Log ' \
--prompt='Branch > ' \
--layout=reverse \
--border=rounded \
--list-border=rounded \
--list-label=' Branches ' \
--scrollbar='' \
--ansi)
if [ -z "$SELECTED" ]; then
exit 0
fi
if git show-ref --verify --quiet "refs/heads/$SELECTED"; then
echo "Switching to local branch: $SELECTED"
git switch "$SELECTED"
else
REMOTE="${SELECTED%%/*}"
BRANCH="${SELECTED#*/}"
if git show-ref --verify --quiet "refs/remotes/$SELECTED"; then
if git show-ref --verify --quiet "refs/heads/$BRANCH"; then
echo "Switching to local branch: $BRANCH"
git switch "$BRANCH"
else
echo "Creating local branch '$BRANCH' tracking '$SELECTED'..."
git switch -c "$BRANCH" --track "$SELECTED"
fi
else
echo "Switching to: $SELECTED"
git switch "$SELECTED" 2>/dev/null || git checkout "$SELECTED"
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment