Created
September 20, 2019 19:08
-
-
Save jeffstephens/18291119a533eab14b0189fb23006184 to your computer and use it in GitHub Desktop.
A handy utility to quickly switch Git branches based on a subsection of its name. e.g. `cob ast` will switch to master.
This file contains 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
# shortcut to invoke git | |
g() { "$(which git)" "$@" ;} | |
# colors for use in normal output with `echo -e` | |
NORMAL_GREEN="\033[0;32m" | |
NORMAL_YELLOW="\033[0;33m" | |
NORMAL_RED="\033[0;31m" | |
NORMAL_CLEAR="\033[0;00m" | |
# checkout a branch given a unique regex pattern | |
cob() { | |
if [ -z $1 ]; then | |
echo "Usage: cob <pattern to match git branch>" | |
echo "Switch to a git branch based on a greppable pattern. Must specify an umambiguous pattern." | |
return 1 | |
fi | |
local pattern=$1 | |
local branchMatches=$(g branch | grep $pattern) | |
# cannot proceed with more than one match | |
local numMatches=$(echo "$branchMatches" | wc -l) | |
if [ $numMatches != 1 ]; then | |
echo -e "${NORMAL_YELLOW}Error: ambiguous pattern. The following branches matched:${NORMAL_CLEAR}" | |
echo "$branchMatches" | |
return 2 | |
fi | |
# cannot proceed with no matches; we don't want to just run `git checkout` | |
if [ -z "$branchMatches" ]; then | |
echo -e "${NORMAL_RED}No matching branches were found. Available branches:${NORMAL_CLEAR}" | |
g branch | |
return 3 | |
fi | |
trimmedBranch=$(echo "$branchMatches" | tr -d '[:space:]') | |
echo -e "${NORMAL_GREEN}Switching to branch ${trimmedBranch}${NORMAL_CLEAR}" | |
g checkout $trimmedBranch | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment