Last active
November 14, 2022 05:42
-
-
Save carlosmcevilly/ea934706c19546c6325cd5ac92a1c53f to your computer and use it in GitHub Desktop.
convenience bash function to git checkout whatever branch matches the passed-in substring
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
# git-co | |
# git checkout whatever branch matches the passed-in substring | |
# | |
# Argument: | |
# substring to match | |
# | |
# Example: | |
# git-co sparkles # checks out the branch whose name contains the substring "sparkles" | |
# | |
# Will abort with an informative message and no action in various error scenarios. | |
# If multiple matches are found, they will be listed but not acted on. | |
# | |
# alpha software, ymmv, feedback welcome. | |
git-co () { | |
local substring=$1 | |
# warn if invoked in wrong place | |
if [[ ! -d ".git" ]]; then | |
echo "not a git directory" | |
return | |
fi | |
# if no arguments, show all the branches we have | |
if [[ -z "$substring" ]]; then | |
git branch | |
return | |
fi | |
local count=$(git branch | grep "$substring" | wc -l) | |
if [[ $count -eq 1 ]]; then | |
local branch=$(git branch | grep "$substring" | sed 's/^ \{1,\}//') | |
local trimmed=$(echo "$branch" | sed 's/^* //') | |
if [[ "$branch" == "$trimmed" ]]; then | |
git checkout "$branch" | |
else | |
echo "already on branch" | |
echo "$trimmed" | |
fi | |
elif [[ $count -eq 0 ]]; then | |
echo "no branches found matching $substring" | |
else | |
echo "mutiple branches found matching $substring:" | |
git branch | grep "$substring" | |
fi | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment