Version control serves as a great way to keep history of the project’s changes, however sometimes we may feel the need to revert back to an original version. Here is how to go about undoing changes in Git.
Although git checkout
is mainly used for checking out branches, you can also use the command to check out commits.
Let’s assume you have the following commit history:
$ git log --oneline
cd7f75f Changed the version number
ae85858 Removed unnecessary text
0acefc1 Initial commit
You can view the ‘Removed unnecessary text’ commit by typing in the following:
$ git checkout ae85858
You can then look at and edit files without worrying losing the current state of the project. Anything you do in this commit will not be saved in your repository. Therefore if you’re working on the master branch, you can head back to the current state of your project:
$ git checkout master
The git revert
command undoes a commit. It should be noted that the commit is not removed from the project’s history, but a new commit is appended with Git figuring out how to undo the changes of the offending commit.
This is useful for a couple of reasons.
git reset
can only work backwards from the current commit.The git reset
command is known as a permanent undo, so it is important to use this command with care.
This command should be used when you need to restore to the last commit locally.
To reset the commit to the previous state before HEAD:
# use --soft if you want to keep your changes
$ git reset --soft HEAD^
# use --hard if you don't care about keeping the changes you made
$ git reset --hard HEAD^
For public commit, you should use the git revert
command which will revert the changes you made in your previous commit.
$ git revert HEAD