Skip to content

Instantly share code, notes, and snippets.

@iul1an
Created February 2, 2026 15:33
Show Gist options
  • Select an option

  • Save iul1an/85126899e48c3fa5c001c4681ef73035 to your computer and use it in GitHub Desktop.

Select an option

Save iul1an/85126899e48c3fa5c001c4681ef73035 to your computer and use it in GitHub Desktop.
Git branch switcher with FZF
#!/usr/bin/env bash
# Check if is git repository
git rev-parse --is-inside-work-tree &>/dev/null || {
echo "Not a git repository"
exit 0
}
# If arguments provided
if [[ $# -gt 0 ]]; then
if [[ $1 == "--all" ]]; then
# List all branches including remotes
BRANCHES=$(git branch --all | awk '!/^[*]/ { $1=$1; print }')
else
# Use the argument as branch name and checkout directly
git checkout "$1"
exit $?
fi
else
# No arguments - list local branches only
BRANCHES=$(git branch | awk '!/^[*]/ { $1=$1; print }')
fi
if [[ -n $BRANCHES ]]; then
BRANCH=$(echo "$BRANCHES" | fzf) || exit 0 # user presses CTRL+c
else
echo "There are no other local branches, only remote ones, use \"--all\""
exit 1
fi
# Handle remote branches (strip "remotes/<remote-name>/" prefix)
if [[ $BRANCH == remotes/* ]]; then
# Extract the remote name and branch name
# remotes/origin/main -> origin/main
REMOTE_AND_BRANCH=${BRANCH#remotes/}
# origin/main -> main
BRANCH_NAME=${REMOTE_AND_BRANCH#*/}
# Checkout the remote branch as a new local branch
git checkout -b "$BRANCH_NAME" "$BRANCH" 2>/dev/null || git checkout "$BRANCH_NAME"
else
# Checkout local branch normally
git checkout "$BRANCH"
fi
@iul1an
Copy link
Author

iul1an commented Feb 2, 2026

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment