Skip to content

Instantly share code, notes, and snippets.

@iwill
Last active October 30, 2023 09:19
Show Gist options
  • Save iwill/88f5835bfc4e58aa1a88 to your computer and use it in GitHub Desktop.
Save iwill/88f5835bfc4e58aa1a88 to your computer and use it in GitHub Desktop.
git checkout with grep patterns
#!/bin/bash
# alias in gitconfig:
# cb = "!sh ~/.git-cb.sh"
# usage:
# git cb ev lo # *ev*lo* - `develop` will be matched
# cb = "!checkoutbranch() { local branches=`git branch | grep -i $1 | tr -d '* '`; if [[ `echo \"$branches\" | wc -l | tr -d ' '` != 1 ]]; then echo \"Matched multiple branches:\"; git branch | grep --color -i $1; exit 1; fi; git checkout $branches; }; checkoutbranch"
branches=`git branch`
color_options="--color"
while [[ $# > 0 ]]; do
branches=`echo "$branches" | grep -i $1`
color_options="$color_options -ie $1"
shift
done
echo "Matched branches:"
echo "$branches" | grep $color_options
branches_count=`echo "$branches" | grep -v "^$" | wc -l | tr -d ' '`
if [[ $branches_count = 1 ]]; then
echo
branch=`echo "$branches" | tr -d '* '`
git checkout "$branch"
elif [[ $branches_count = 0 ]]; then
exit 1
else
exit 2
fi
@iwill
Copy link
Author

iwill commented Aug 19, 2015

install

wget https://gist.github.com/iwill/88f5835bfc4e58aa1a88/raw/c4c5c538c957aa369c60b9520f9e45d7d89761da/git-cb.sh -O ~/.git-cb.sh

git config

add alias to ~/.gitconfig:

[alias]
    cb = "!sh ~/.git-cb.sh"

more

@see git-completion https://github.com/git/git/tree/master/contrib/completion

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment