Skip to content

Instantly share code, notes, and snippets.

@virtualstaticvoid
Last active September 1, 2022 13:26
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 virtualstaticvoid/0e1b35665588aa928e86b882daec5f4c to your computer and use it in GitHub Desktop.
Save virtualstaticvoid/0e1b35665588aa928e86b882daec5f4c to your computer and use it in GitHub Desktop.
git-reset-branch
#!/bin/bash
#
# Description:
#
# Resets the local branch which has diverged from it's tracking (remote) branch
# can also be used to switch over from "master" to "main" branch
#
# Usage:
#
# git reset-branch
# git reset-branch main
# git reset-branch main origin/main
#
# fail fast
set -e
if [[ ! -d .git ]]; then
printf "\033[1;31mERROR\033[0m: Run this script from the project root which contains the .git directory.\n"
exit 1
fi
# get the branch, defaults to the current branch name
branch=${1:-$(git rev-parse --abbrev-ref HEAD)}
# get tracking branch, defaults to the configured tracking branch
tracking=${2:-$(git rev-parse --abbrev-ref --symbolic-full-name @{u} 2>&1 || echo "")}
if [[ -n "$tracking" ]]; then
printf "\033[1;32mINFO\033[0m: Resetting \033[1m$branch\033[0m to \033[1m$tracking\033[0m branch.\n"
git reset --hard
git checkout -b tmp
git branch -D $branch
git checkout -b $branch $tracking
git branch -D tmp
else
printf "\033[1;31mERROR\033[0m: Unable to reset branch without a remote tracking branch.\n"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment