Skip to content

Instantly share code, notes, and snippets.

@svandragt
Created June 13, 2023 09:34
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 svandragt/d43e4aebcca402754cd2c6c276558eb6 to your computer and use it in GitHub Desktop.
Save svandragt/d43e4aebcca402754cd2c6c276558eb6 to your computer and use it in GitHub Desktop.
Fuzzy switcher, handles checking out origin branches.
#!/usr/bin/env bash
# filename: ~/bin/git-sw
# example: git sw 930
# example: git sw origin/JIRA-2
#
# Fuzzy switch
# TODO: Does not handle remotes other than origin.
# Check branch locally
BRANCH=$(git branch | grep $1 | head -n1 | xargs)
ORIGIN_BRANCH=''
if [ -z "$BRANCH" ]; then
# Check remote branch if the branch does not exist locally.
BRANCH=$(git branch --remote | grep $1 | head -n1)
fi
# Handle requests for origin branches, or for branches that are found in the remote:
# Trim branch name
BRANCH="$(echo $BRANCH | xargs)"
if [[ $BRANCH == origin/* ]]; then
ORIGIN_BRANCH=$BRANCH
# Derive branch name by removing origin/
BRANCH=$(echo "$BRANCH" | sed 's/^origin\///')
fi
echo "$BRANCH $ORIGIN_BRANCH"
git switch -C $BRANCH $ORIGIN_BRANCH; git fetch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment