Sometimes you want to undo certain changes or view a previous state of a file. Git makes this possible for us.
There are several scenarios:
In this case we can undo the changes with the checkout command:
$ git checkout path/to/file
This way the changes will be undone. Keep in mind that there is no redo possible, once the changes have been undone they are gone.
We can get rid of the commit by resetting the branch state. The “HEAD” of a branch is always the latest commit. We can set the HEAD to an older commit, but keep in mind that if you do this all commits in between will be lost as well.
Always consider using the “revert” command explained in the next section instead of resetting.
$ git reset --soft HEAD~1
The command above will place the HEAD one commit back. The changes are still here (as files that have changes but are not staged for commit), but the commit is gone.
$ git reset --hard HEAD~1
Using the --hard option will place the HEAD back and getting rid off the changes and the commit(s).
You can replace HEAD~1 with HEAD~3 if you want to go back 3 commits. Or use a commit hash to specify to which commit the HEAD should point at.
*** Never do this when the commits have already been pushed ***
We can “revert” the changes. This is the preferred way to undo changes that have been committed.
Reverting changes will not get rid of any commits. Instead it will add another commit that reverts the files involved to their state before the commit. A big advantage to this is that you can revert a revert (basically undoing the commit).
$ git revert HEAD~1
This will revert the second last commit. Undoing the changes and adding a new commit. You can also use one or more commit hashes instead of HEAD~1.
Sometimes we need see an older revision of all files in the repository, but not actually undo any changes.
We can do this with the checkout command:
$ git checkout <commit-hash>
This will bring all the files back to the state they were in after the commit we specified.
To go back to the current state we can use the checkout command again, this time specifying the branch name we were working on:
$ git checkout <branch-name>
Sometimes we just want to see an older revision of a file, but keep the other files in the current state.
We can do that with the same checkout command as above, but adding the file name:
$ git checkout <commit-hash> path/to/file
This will bring the file back the state it was in after the specified commit.
To return the file back to its current state:
$ git checkout HEAD path/to/file