Skip to content

Instantly share code, notes, and snippets.

@slugbyte
Last active February 23, 2016 00:55
Show Gist options
  • Save slugbyte/9a334e213b766ebd1a8d to your computer and use it in GitHub Desktop.
Save slugbyte/9a334e213b766ebd1a8d to your computer and use it in GitHub Desktop.

Rolling Back A Branch

Issue

  • You have been working on a project in a branch called branch_name and your code is not working.
  • You have spent some time trying to fix your code and its going no where.
  • You come to the conclusion that it would be better if you could start over from an earlier commit.
  • You want to roll back, but you dont want to loose any of your history.

Step by Step Solution

  1. Navigate to your project in your shell (the command line).
  • $ cd /path/to/your/project
  1. Make sure you are in the correct branch.
  • $ git branch
    git will list local branches and put a * infront of the branch you are in
  1. Make sure you have notthing to commit. If you have uncommited changes, commit them.
  • $ git status
    nothing to commit, working directory clean
  1. Make a backup of your branch named origial-branch-name + -backup so you have a copy of the history.
  • $ git checkout -b <branch-name-backup>
  1. Switch back to your original branch.
  • $ git checkout <branch-name>
  1. Look at your logs and find the commit that you want to roll back to.
  • $ git log
  • Copy the hash of the commit you want to roll back.
    the hash should look like dfbc904ac5677a326598408116fe729f7eb667b0
  1. roll back the branch to the hash copied from the log
  • $ git reset --hard dfbc904ac5677a326598408116fe729f7eb667b0
    HEAD is now at dfbc904 <commit message> from <username>/<branch-name>
  1. You have rolled back your local branch!
  2. If you have a remote repository on github, you need to push the current state of your branch to the remote, and update your local copy of the remote repository.
  • do not do this step if you have not created a backup of your branch
  • $ git push origin <branch-name> --force
  • $ git fetch origin
  1. You have rolled back your local branch, remote branch, and local copy of your remote repository!

You rolled back to far, and want to undo your roll back.

  1. Navigate to your project in your shell (the command line).
  • $ cd /path/to/your/project
  1. Make sure you are in the correct branch.
  • $ git branch
    git will list local branches and put a * infront of the branch you are in
  1. Make sure you have notthing to commit. If you have uncommited changes, commit them.
  • $ git status
    nothing to commit, working directory clean
  1. Merge your backup-branch into the branch you rolled back.
  • $ git merge branch-name-backup
  1. You have now successfully undone your roll back.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment