Created
February 2, 2026 15:33
-
-
Save iul1an/85126899e48c3fa5c001c4681ef73035 to your computer and use it in GitHub Desktop.
Git branch switcher with FZF
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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 |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
dependencies: