Git: How to revert a specific file to an old version

Updated: January 27, 2024 By: Guest Contributor Post a comment

Introduction

Git is a powerful tool for version control that enables developers to keep track of changes to their files over time. Sometimes, you may find yourself needing to look back in time and return a specific file to a previous version without affecting other parts of your project. This tutorial will discuss how to revert a file to a previous version in Git, starting from the basics and moving towards more advanced scenarios.

Preparing to Revert a File

Before we begin, ensure that you have Git installed on your system and that you’ve initialized a Git repository where your project is stored. Open a terminal or command prompt and navigate to your project directory:

cd /path/to/your/project

To check the history of your file commits, use:

git log -- path/to/your/file

With that, you’re ready to start reverting files to old versions.

Revert a specific file to a previous commit

To restore a file to the version stored in a specific commit, you’ll need to know the commit hash. Start by retrieving the list of commits that include changes to your specific file:

git log --oneline path/to/file

This will shorten the commit ids with their corresponding messages. Look for the commit hash of the version you want to restore. Now, revert the file:

git checkout  -- path/to/file

Verify the file has been reverted to the old version:

git diff path/to/file

Using ‘git reset’ to revert changes

If you want to unstage a file that you’ve staged incorrectly and restore it to the version in the last commit, use ‘git reset’:

git reset HEAD path/to/file

‘HEAD’ refers to the last commit on the current branch. The file will now revert to its last committed state.

Reverting multiple files to a previous commit

If you need to revert multiple files to the status of a previous commit, you can achieve this with a single command:

git checkout  -- path/to/file1 path/to/file2

Replace ” with the hash of the commit you’re targeting and ‘path/to/file1’, ‘path/to/file2’, etc., with the paths of the files you want to revert.

Advanced: Reverting changes using a new commit

Sometimes, you may want to create a new commit that reverts the changes of a past commit for a specific file. Here’s how you can do it:

git revert --no-commit .

This command will revert the changes, but not commit them, allowing you to revert multiple commits or adjust the revert before finalizing it with a commit.

Conclusion

In this tutorial, we’ve learned several ways to revert a specific file to a previous version using Git. Whether it’s a quick fix using ‘git checkout’ for a single file, or using ‘git revert’ to undo changes while preserving the history, Git provides multiple options to suit your version control strategy. With careful management of commits and file versions, Git becomes an invaluable tool for maintaining the integrity of your project code.