Skip to content

Instantly share code, notes, and snippets.

@yaronuliel
Last active Jan 16, 2018
Embed
What would you like to do?
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