Efficiently Reverting a Single File to a Specific Commit in Git and GitHub


Git and GitHub serve the purpose of storing your old code, allowing you to roll back in case of issues and safely restore previous and accurate code.

When collaborating with other developers, it also becomes essential to know how to revert a single file to a specific commit. This is because, while working on a feature, you might need to modify unrelated files to test it. Manually changing each line of code in those files and creating a new commit can result in a cluttered commit history. Reverting the file is a much cleaner approach.

Finding the Commit ID

First, navigate to the shared repository on GitHub and locate the file you want to revert. Just above the file, you should see a 7-digit commit ID and a date, indicating the most recent commit in which the file was modified. Note down or copy this commit ID, such as the one shown below:

Now how to check the actual file for different commits? First click the “history” and expand, you will see all the commits related to this file:

Now choose any commit ID you want to revert, then click the ‘…’ button, and choose the “view file”, and check the actual file:

Locating the File Path

Next, you need the path to the file from the working directory. This can be found on the same GitHub screen where you discovered the commit ID for the file. Make sure to only copy the path without the working directory name, as it will be the directory you’re in when using this file path.

Reverting the File

With the terminal open and the working directory set, use the git checkout command to revert the file. The format of the git command should look like this:

git checkout [commit ID] -- path/to/file
or this specific case, it will be:
git checkout 4a023a6 -- gpt4-novel/readme

Committing the Change

After reverting the file, it’s necessary to commit the change, which, in this case, is a revert of a single file. This can be done using the standard commit command:

git commit -m 'commit message'

Finally, push the commit to the remote repository so that the GitHub version of your branch matches your local version.


Author: robot learner
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source robot learner !
  TOC