Skip to content

Instantly share code, notes, and snippets.

@Bhacaz
Last active September 25, 2025 00:51
Show Gist options
  • Save Bhacaz/c00f7174918c00b5ab3a5af080fece04 to your computer and use it in GitHub Desktop.
Save Bhacaz/c00f7174918c00b5ab3a5af080fece04 to your computer and use it in GitHub Desktop.
git-branch-select.sh
[alias]
bs = git-branch-select.sh

Interactive and searchable branch checkout

  1. Install fzf brew install fzf
  2. Copy the script git-branch-select.sh somehwere in your PATH like ~/.local/bin in macos
  3. Make is executable chomd +x path/to/git-branch-select.sh
  4. Add a git alias in ~/.gitconfig with your path to exectute the script
  5. git bs
image
#!/bin/bash
# Interactive git branch selector
# Shows local branches sorted by last modified date
# Use arrow keys to navigate, Enter to checkout
set -e
# Check if fzf is installed
if ! command -v fzf &> /dev/null; then
echo "Error: fzf is required but not installed."
echo "Install it with: brew install fzf (on macOS) or your package manager"
exit 1
fi
# Get current branch to highlight it
current_branch=$(git branch --show-current)
# Get local branches sorted by last commit date (most recent first)
# Format the display line directly
branches=$(git for-each-ref --sort='-committerdate' --format='%(refname:short)|%(committerdate:relative)|%(subject)' refs/heads/ \
| while IFS='|' read -r branch date subject; do
if [ "$branch" = "$current_branch" ]; then
printf "* %-50s (%s)\n" "$branch" "$date"
else
printf " %-50s (%s)\n" "$branch" "$date"
fi
done)
# Use fzf to select branch interactively
# Use --nth to search only on the branch name part (before the parentheses)
selected=$(echo "$branches" | fzf \
--height=40% \
--layout=reverse \
--border-label ' Git Branch Select ' \
--border \
--padding 1,1 \
--input-label=' Select Branch ' \
--no-info \
--color 'border:#6699cc,label:#99ccff' \
--preview-border=none \
--preview-window=right:30%,noinfo \
--preview='
branch=$(echo {} | sed "s/^[* ] *//" | cut -d" " -f1)
git log --oneline --graph --color=always -15 "$branch"
' \
--header="↑↓ navigate • Enter: checkout • Esc: cancel" \
--bind="enter:accept" \
--no-multi \
--nth=1 \
--delimiter=' (' \
--no-sort)
# Exit if no selection made (user pressed Esc)
if [ -z "$selected" ]; then
echo "No branch selected. Exiting."
exit 0
fi
# Extract branch name from selection
branch_name=$(echo "$selected" | sed 's/^[* ] *//' | cut -d' ' -f1)
# Don't checkout if already on the selected branch
if [ "$branch_name" = "$current_branch" ]; then
echo "Already on branch '$branch_name'"
exit 0
fi
# Checkout the selected branch
echo "Checking out branch: $branch_name"
git checkout "$branch_name"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment