Skip to content

Instantly share code, notes, and snippets.

@dominic-rossi
Created May 1, 2017 18:16
Show Gist options
  • Save dominic-rossi/e875b96755357c29594124746b6721a8 to your computer and use it in GitHub Desktop.
Save dominic-rossi/e875b96755357c29594124746b6721a8 to your computer and use it in GitHub Desktop.
GCO
#!/bin/bash
# Validate the input
if [ "$#" -ne 1 ]; then
printf "Enter a branch number only\n"
exit
fi
# Special case if the argument is "-"
if [ $1 = "-" ];
then
git checkout -
exit
fi
function checkout {
# Check how many branches with that number exist
num_branches=$(echo $branch | wc -w)
if [ "$num_branches" -gt 1 ];
then
printf "Too many branches exist:\n\n$branch"
printf "\n\nTry being more specific\n"
else
# Strip off remotes/origin/ prefix if necessary
if [[ $branch == remotes/origin/* ]]
then
branch=${branch#remotes/origin/}
fi
# Check that no local changes exist before switching branches
changed_files=$(git status --porcelain --untracked-files=no | wc -l)
# Check that we are not already on the branch
if [ "$current_branch" = "$branch" ];
then
printf "Already checked out $branch\n"
#elif [ $changed_files -gt 0 ];
#then
# printf "Uncommitted changes detected. Try stashing or committing first.\n"
else
git checkout $branch
fi
fi
}
current_branch="$(git rev-parse --abbrev-ref HEAD)"
branch=$(git branch -a | grep -v remotes | grep -e $1 | tr -d " *")
remote_branch=$(git branch -a | grep remotes | grep -e $1 | tr -d " *")
if [ -n "$branch" ];
then
checkout
elif [ -n "$remote_branch" ];
then
branch=$remote_branch
checkout
else
printf "Could not find branch containing $1\n"
fi
@VaughnGH
Copy link

Wonderful.

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