Skip to content

Instantly share code, notes, and snippets.

@joaocarmo
Last active September 13, 2021 12:13
Show Gist options
  • Save joaocarmo/ef9f1eeb09c0a51915bdc37685ed5d81 to your computer and use it in GitHub Desktop.
Save joaocarmo/ef9f1eeb09c0a51915bdc37685ed5d81 to your computer and use it in GitHub Desktop.
Interactively checkout local branches (git)
#!/bin/bash
################################################################################
# Interactive Git Checkout
# ------------------------------------------------------------------------------
# Author: Joao Carmo
# License: MIT
# ------------------------------------------------------------------------------
# This script will list all available local branches and you can select one to
# checkout using a number (on the list).
################################################################################
# Variables / Settings
current_b=$(git rev-parse --abbrev-ref HEAD 2>/dev/null)
local_b=$(git branch 2>/dev/null | awk -F ' +' '! /\(no branch\)/ {print $2}')
master_b='master'
RED='\033[0;31m'
GREEN='\033[0;32m'
NOCOLOR='\033[0m'
branches=()
num=0
co_branch=
base_dashes=18
DASH='*'
SEPR='**'
# Functions
function repl {
local ts=$(printf "%${2}s")
printf %s "${ts// /$1}"
}
function listb {
IFS=$'\n' read -rd '' -a branches <<<"$1"
for branch in "${branches[@]}"; do
if [ "$branch" = "$current_b" ]; then
HIGHLIGHT=$GREEN
elif [ "$branch" = "$master_b" ]; then
HIGHLIGHT=$RED
else
HIGHLIGHT=$NOCOLOR
fi
num=$(($num + 1))
printf " %5s ${HIGHLIGHT}%s${NOCOLOR}\n" "[$num]" "$branch"
done
TOTAL=$num
printf "\n"
}
function gitcheckout {
git checkout "$1"
}
# Main
if [ ! -z "$current_b" ] && [ ! -z "$local_b" ]; then
# Display the current branch
branch_str_len=${#current_b}
printf "${SEPR}"
repl "${DASH}" $(($base_dashes + $branch_str_len))
printf "${SEPR}\n"
printf "${SEPR} Current branch: ${GREEN}%s${NOCOLOR} ${SEPR}\n" "$current_b"
printf "${SEPR}"
repl "${DASH}" $(($base_dashes + $branch_str_len))
printf "${SEPR}\n"
# List local branches
printf "\n"
printf " Local branches:\n"
listb "$local_b"
printf "\n"
printf "Select the branch to checkout (number): "
read choice
printf "\n"
if [ "$choice" -gt "0" ]; then
co_branch=${branches[$(($choice - 1))]}
if [ ! -z "$co_branch" ]; then
gitcheckout "$co_branch"
else
>&2 printf "Error: Invalid selection\n"
exit 1
fi
else
>&2 printf "Error: Invalid selection\n"
exit 1
fi
else
>&2 printf "Error: Not in a .git repository\n"
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment