Skip to content

Instantly share code, notes, and snippets.

@KeyboardCowboy
Last active February 28, 2017 19:41
Show Gist options
  • Save KeyboardCowboy/9fd15231f730eed7fd06a9bf55a53767 to your computer and use it in GitHub Desktop.
Save KeyboardCowboy/9fd15231f730eed7fd06a9bf55a53767 to your computer and use it in GitHub Desktop.
Shortcut to checkout a feature branch from a ticket number.
#!/usr/bin/env bash
#
# Shortcut to checkout a feature branch from a ticket number.
KEY=-1
SEARCH=$1
# Require a parameter.
if [[ -z "$SEARCH" ]]; then
echo "What are you searching for?"
exit 1
fi
echo "Looking for branches with $SEARCH"
# Look for the pattern in git branches.
BRANCHES=(`git branch | grep $SEARCH`)
# Split up multiple results.
LIST=("EXIT")
# Why is this loading all files and directories as well as git branches?
#echo "${#BRANCHES[@]} items in branches"
# Exit of there are no matching branches.
if [ ${#BRANCHES[@]} == 0 ]; then
echo "No branches matching $SEARCH."
exit 0
fi
# If only one matching branch was found, check it out.
if [ ${#BRANCHES[@]} == 1 ]; then
echo "Found 1 branch matching $SEARCH."
git co $BRANCHES
exit 0
fi
# There are multiple options, so give the user a choice.
echo "Found ${#BRANCHES[@]} possible matches..."
LIST=("${LIST[@]}" "${BRANCHES[@]}")
CNT=${#LIST[@]}
# Make sure the user picks a valid number.
while [[ $KEY < 0 ]] || [[ $KEY > $CNT ]]; do
for (( i=0; i<${CNT}; i++ )); do
ITEM=${LIST[$i]}
echo "[$i] : $ITEM"
done
read -p "Choose a branch to checkout: " KEY
done
# Checkout the desired branch.
if [ $KEY == 0 ]; then
echo "Nevermind."
else
git checkout ${LIST[$KEY]}
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment