Reverting to Previous Versions in Git

This is a follow-up to my other post on contributing to a project on Git. Whereas the other post dealt with pulling, commiting, and pushing, this post covers reverting to a previous version.

Viewing a Previous Version

View the previous version of a specific file.

git show HEAD~1:path/to/file

Or view all the files in the second (or n-th) commit back in time.

git show HEAD~2

You can use git log to see all of the commits. You can refer to specific commits using the hash value in the log using the following formula,

git show <HASH>:path/to/file

Or you can use a relative “path” back in the commit history using the ~n pattern.

git show "<HASH>~n":path/to/file

Viewing the Difference Between Two Versions

You can view the difference between the current version and the previous version using the diff keyword

git diff path/to/file

You may also compare the current version to an arbitrary version in the commit history using the commit hash

git diff <HASH> path/to/file

Reverting to a Previous Version

Once you’re happy that you’ve found the version that you’d like to rever to, then you can revert to that version using the checkout command,

git checkout <HASH> path/to/file

Alternatively, you can use the ~n pattern, with the commit hash value, or the HEAD keyword.

Leave a Reply

Your email address will not be published. Required fields are marked *