Skip to content

Instantly share code, notes, and snippets.

@yaronuliel
Last active January 16, 2018 12:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yaronuliel/e15084fe1ca35172932dbb1b9baaf15f to your computer and use it in GitHub Desktop.
Save yaronuliel/e15084fe1ca35172932dbb1b9baaf15f to your computer and use it in GitHub Desktop.
Git checkout by partial branch name or from list - `git ch`
#!/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
@yaronuliel
Copy link
Author

yaronuliel commented Jan 16, 2018

Installation

  1. download raw file into a folder in your PATH
  2. Make the file executable 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:

     1	  production
     2	  staging
     3	* master

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 shown

     1    BUG-1132-some-very-long-name
     2    BUG-3211-a-complicated-branch-name
     3    FEATURE-33132-new-account-page
     4  * master

you 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

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