Skip to content

Instantly share code, notes, and snippets.

@soulim
Last active March 4, 2020 09:30
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 soulim/2c0364d411f8e6a8a470a56a66d4d07d to your computer and use it in GitHub Desktop.
Save soulim/2c0364d411f8e6a8a470a56a66d4d07d to your computer and use it in GitHub Desktop.
Switch to any git branch interactively
#!/usr/bin/env sh
# git-goto: Switch to any git branch interactively.
#
# If the script is discoverable via PATH, then git will pick it up and make it
# available as `goto` subcommand.
#
# Dependencies:
#
# - fzf, https://github.com/junegunn/fzf
#
# Example:
#
# # NOTE: the script is located in `~/.bin` directory
# # which is included into PATH.
#
# git goto
set -o errexit # Always exit on error
set -o nounset # Treat unset variables as errors
# List all git branches (including remote) except current and HEAD.
# Additionally remove all leading spaces for each line of the list.
branches=$(git branch --all | grep --invert-match --extended-regexp "^\*|HEAD" | sed "s/.* //")
# Select a branch to switch to using interactive fuzzy search applied to
# the list of branches.
#
# If one of remote branches is selected, then remove `remotes/*/` prefix
# from the name, e.g. `remotes/origin/foo-bar` becomes `foo-bar`
branch=$(echo "$branches" | fzf --height=20% | sed "s#remotes/[^/]*/##")
# Switch to a selected branch.
if [[ -n "$branch" ]]
then
git checkout "$branch"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment