Last active
January 16, 2018 12:41
-
-
Save yaronuliel/e15084fe1ca35172932dbb1b9baaf15f to your computer and use it in GitHub Desktop.
Git checkout by partial branch name or from list - `git ch`
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
#!/usr/bin/env bash | |
get_branches="git branch | sort -u" | |
if [[ $# -eq 0 ]] ; then | |
eval "$get_branches | nl -ba" | |
exit; | |
fi | |
branch_num=$1 | |
branch="" | |
error_msg="Error: Did not find any matching branch" | |
re='^[0-9]+$' | |
if [[ $branch_num =~ $re ]] ; then | |
# get branch name - if the branch is current remove the * sign | |
branch=$(eval "$get_branches | sed -n '${branch_num}p' | sed 's/^\*/ /'") | |
if [[ -z $branch ]] ; then | |
# Continue searching for number in branch name, if not found - present this error message | |
error_msg="Error: invalid branch number" | |
fi | |
fi | |
# If nothing found yet - try grepping for the result | |
if [[ -z $branch ]]; then | |
matching_branches=$(eval "$get_branches | sed 's/^\*/ /' | grep -i $1") | |
lines=$(grep -c . <<<"$matching_branches") | |
if (( $lines > 1 )); then | |
eval "$get_branches | nl -ba | grep -i \"$1\"" | |
exit | |
fi | |
branch="$matching_branches" | |
fi | |
# Host is Empty | |
if [[ -z $branch ]] ; then | |
echo "$error_msg" >&2 | |
exit 1 | |
fi | |
echo "Switching to $branch" | |
git checkout $branch |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Installation
chmod +x git-ch
Use
From list
When in a git repo dir, run
$ git ch
You should see a list of available local branches. For example:
to checkout the
staging
branch for example - run$ git ch 2
By partial name
If you remember part of your branch's name, or is it too long - you can checkout the branch by entering part of the name,
for example, if
$ git ch
shownyou can switch to the
BUG-1132-some-very-long-name
branch by simply executing$ git ch bug-1132
Note - the script currently supports only local branches. To checkout a branch for the first time - you should use the native
$ git checkout BRANCH-NAME
command with the full branch name