- 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.
- Navigate to your project in your shell (the command line).
$ cd /path/to/your/project
- 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
- Make sure you have notthing to commit. If you have uncommited changes, commit them.
$ git status
nothing to commit, working directory clean
- 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>
- Switch back to your original branch.
$ git checkout <branch-name>
- 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
- 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>
- You have rolled back your local branch!
- 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
- You have rolled back your local branch, remote branch, and local copy of your remote repository!
- Navigate to your project in your shell (the command line).
$ cd /path/to/your/project
- 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
- Make sure you have notthing to commit. If you have uncommited changes, commit them.
$ git status
nothing to commit, working directory clean
- Merge your backup-branch into the branch you rolled back.
$ git merge branch-name-backup
- You have now successfully undone your roll back.