Skip to content

Instantly share code, notes, and snippets.

@brendacs
Last active March 12, 2020 20:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brendacs/0c5fd8e764d023f90108e65c5280d279 to your computer and use it in GitHub Desktop.
Save brendacs/0c5fd8e764d023f90108e65c5280d279 to your computer and use it in GitHub Desktop.
Switch git branches by number
# Get all branch names
all_branches=`git for-each-ref --shell \
--format='%(refname:strip=2)' refs/heads | \
cut -d "'" -f 2`
# Print branch names with assigned number
arr=($all_branches)
# Assigned number is branch's actual index + 1
idx=1
for branch in ${arr[@]}; do
echo $idx $branch
((idx++))
done
# User picks branch by number or enters new
echo Enter branch number or 0 to create a branch:
read number
# Create new branch with given name and switch to it
if [ "$number" == 0 ]; then
echo "Enter branch name"
read new_name
echo "Creating new branch $new_name"
git checkout -b "$new_name"
exit
fi
# Switch to branch picked if valid and exit
if [ ${arr["$number - 1"]} ]; then
echo Switching to ${arr["$number - 1"]}
git checkout ${arr["$number - 1"]}
exit
fi
echo Branch number "$number" not found
# Start backup flow to pick branch by name
echo Enter branch name:
read name
echo Switching to "$name"
# Get branch that matches the name
matching_branch=`git for-each-ref --shell \
--format='%(refname:strip=2)' refs/heads | \
grep "\${name}\>" | cut -d "'" -f 2`
# Switch to branch if it exists and exit
if [ "$matching_branch" ]; then
git checkout "$matching_branch"
exit
fi
# Create new branch flow
echo No branch named "$name" found
echo "Create new branch named $name? (y/n)"
read answer
if [ "$answer" == 'y' ]; then
echo Creating new branch "$name"
git checkout -b "$name"
fi
exit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment