Git Revert File to Previous Commit: How to Do It?
Last Updated on September 16, 2024
Everyone who uses version control systems sooner or later has to face the task of restoring a specific version of one particular file at some point. Understanding the commit history is crucial when using Git commands to manage changes effectively. Frequently, it must also be a single file from several versions before. The built-in tools in Git allow such operations, but whoever uses them often knows that the –force flag when using git checkout or the git reset –hard git command is handy.
Let’s solve our problem once and for all. So, there is no need for you to search for ‘how to git revert file to the previous commit (or last commit)” on the internet.
How to git revert file to previous commit
In the case of Git, we know that we have the git checkout command at our disposal, and thanks to it, we can restore the specific file to the desired state using the script presented in Listing 1.
The script presents various approaches to searching for a change of interest and uses the git checkout command. The command git checkout file can revert a file to a previously committed version without affecting the HEAD reference, allowing users to discard recent changes while still being able to inspect previous states of the file. Additionally, the command git checkout HEAD foo can be used to manage file revisions by checking out a specific file or version from the HEAD of the repository, making it practical for recovering previous versions of files without committing unwanted changes. In the first and third approaches, we have to choose which specific commit is the target commit at some point. Thanks to this, we can find and select the most appropriate version, but it should be noted that we have to choose the correct change ourselves using the git log and git diff commands. You should also remember that we can restore with the command git ls-files -d | xargs git checkout — files in a given folder.
What with special cases?
Here’s a little mystery, does this command work on deleted files with the git rm command? The truth is, however, that we don’t have to worry about such questions anymore because GitProtect DevOps backup is there to solve it for us!
$ git init
# We need to find here a change that interests us.
$ git log --diff-filter=D --summary
$ git checkout 9ad202d538c6ee6448e2c1ca1529f0e78edd3f86~1 -- kafej.xml
--or--
$ git init
# We will restore to the last version of the file here.
$ git rev-list -n 1 HEAD -- kafej.xml
$ git checkout 9ad202d538c6ee6448e2c1ca1529f0e78edd3f86~1 -- kafej.xml
--or--
$ git init
# find interesting us commit
$ git log
# review the changes made to a file
$ git diff 9ad202d538c6ee6448e2c1ca1529f0e78edd3f86 kafej.xml
$ git reset 9ad202d538c6ee6448e2c1ca1529f0e78edd3f86 kafej.xml --hard
Listing 1. Finding and restoring files with the git checkout command.
Git checkout and git restore – a quick introduction
We must also remember that the git checkout command is not the only built-in tool in Git that will allow us to restore changes, undo things or modified file, etc.
Another exciting command that we can use is git restore. Still, you have to remember that even the official Git documentation says that this tool is experimental, and you should never forget that. The name can be confusing, too, as using git restore is not used to undo changes to a repository but to undo local changes to a local disk. This means that we can, for example, undelete deleted files from the local disk from the git repo, but not files in the git repository itself.
$ git status
On branch master
Your branch is ahead of 'origin/master' by 3 commits.
(use "git push" to publish your local commits)
Changes are not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>... " to discard changes in the working directory)
modified: kafej.xml
$ git restore kafej.xml
Listing 2. Using the git restore command to restore a local file from a repository.
How to revert a file with git revert?
Another interesting tool is git revert, which will allow us to undo the changes and leave a note about them. This means that it can make a git restore of the changes from a given git commit and at the same time make a new commit that undoes the changes made by a previous commit. It is important to include a clear commit message when committing changes after a revert to document the nature of the changes made, particularly when pushing to a remote repository. Thanks to this property this command is used very often. Thus, we can keep documentation and information about our project according to actual events.
Why choose git revert
This approach is very desirable and very similar to supporting Electronic Document Management (EDM), one of the main assumptions of complete transparency about changes in documents. This approach is mentioned as one of the best practices in creating projects.
$ git init
$ git add kafej.xml
$ git commit
hint: Waiting for your editor to close the file...
[master (root-commit) 0672413] Add file
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 kafej.xml
$ git log
commit 06724135d660b9afbde334e61f98113349b52f48 (HEAD -> master)
Author: Kafej <[email protected]>
Date: Sat May 29 16:55:14 2021 +0200
Add file
$ git revert 06724135d660b9afbde334e61f98113349b52f48
Removing kafej.xml
hint: Waiting for your editor to close the file...
[master 8c9440d] Revert "Add file"
1 file changed, 0 insertions(+), 0 deletions(-)
delete mode 100644 kafej.xml
$ git log
Author: Kafej <[email protected]>
Date: Sat May 29 16:56:38 2021 +0200
Revert "Add file"
This reverts commit 06724135d660b9afbde334e61f98113349b52f48.
commit 06724135d660b9afbde334e61f98113349b52f48
Author: Kafej <[email protected]>
Date: Sat May 29 16:55:14 2021 +0200
Add file
Listing 3. An example of using the git revert command.
Beyond git revert and co. – trust in backup
Okay, but is it not the case that all these commands can be confusing, and what if we use git reset –hard and understand that this isn’t the git commit command that we wanted after all?
Git commit, git rollback, git force rollback, git reset command and more… – it’s always good to know your git commands. But there is a fine line between day-to-day programming and security policies and data protection in general. A professional backup solution heavily oriented on the DevOps ecosystem is what you really need when it comes to securing your source code and related metadata.
GitProtect – the 1st professional DevOps backup with true Disaster Recovery
GitProtect backup and Disaster Recovery software offers you support for git hosting providers like GitHub, Bitbucket and GitLab, Jira. You get automatic backups with the automatic repository sync – by specific time interval or on-demand. GitProtect gives you full control over retention, compression, encryption, backup window, start delay, and much more. This is also the only solution on the market that offers real Disaster Recovery, ransomware protection, and many restore option, like granular restore, multiple repositories restore, and crossover recovery.
What to read next? Pull request vs. merge request: what’s the difference, best use cases, and examples.
Frequently Asked Questions:
How do I revert an amended commit?
To revert a git commit -amend, you should first check the commit history and locate the amended commit. For that, you can use ‘git log’. Thus, you will identify both the amended commit and the one before it.
Then, use ‘reset -hard’ or ‘git reset -soft’ to reset the previous commit. Be cautious with ‘git reset -hard’ though, since it will also reset your actual working directory to that previous commit, as well. It is always better to back up work whenever you use hard resets to make sure that your branch and other related data are safe. In case you want to keep your working directory changes, use ‘git reset -soft’.
Finally, verify if the reset process was successful with ‘git reflog’. You should see that the amended commit is not at the top anymore. It’s a good practice to run ‘git status’ and check if the changes from the commit you amended are staged to avoid potential mistakes.
How do I remove a file from a commit?
To remove a file from a commit you can use ‘git reset -soft’ and then determine the commit before HEAD. The command is as follows: ‘git reset –soft HEAD~1’. As a result, you should see files from your most recent commit and therefore, you can commit them. You have your files in the staging area now, so you can move on to removing or unstaging them, with the aforementioned ‘git reset’ command: ‘git reset HEAD <file>’.
Then, to delete the file completely from your staging area, you can do so with the ‘git rm’ command: ‘git rm –cached <file>’. Once that’s done, you can move on to committing the changes made by using the ‘amend’ option: ‘git commit –amend’. And finally, you should make sure the files were successfully deleted from your repo. To do so, run the ‘git ls-files’ command – which will show you if the file still exists in the file:
‘git ls-files
<file1>
<file2>
How do I remove a file from the git commit after push?
The initial steps to delete a file from a git commit are the same whether it has been pushed or not. To start off, you need to check out the past, unchanged state of your file: ‘git checkout HEAD^ — /path/to/file’. Then, you commit: ‘git commit -am “revert changes on this file, not finished with it yet”’. Now, you can simply push it without the need for force push: ‘git push’. Once these steps are done, you can refer back to your unfinished work, and run the following: ‘git checkout HEAD^ — /path/to/file’.
Another method to remove a file change from the last commit is ‘uncommitting’. To revert your file to the state prior to the last commit, run: ‘git checkout HEAD^ /path/to/file’. Next, you can update the last commit with your reverted file with: ‘git commit –amend’. Finally, you push the updated commit to your repository using: ‘git push -f’.
Can you revert a single file from a commit?
Yes, you can. The simplest method is ‘git checkout’. Find the commit hash and the path to the file you want to revert, then run the following command: ‘git checkout <commit_hash> — <path/to/file>’. Replace ‘<commit_hash>’ with the actual commit hash and ‘<path/to/file>’ with the path to the file you seek to revert. Next, stage the changes with ‘git add’, commit them using ‘git commit -m “Revert changes to <file>” and you can now push the changes to your remote repo with ‘git push’.
Another way is through the use of ‘git revert’ – this method grants a cleaner commit history, as when changes are undone from a chosen commit you get a new commit with the revert. Locate the commit hash that brought in the unwanted changes. Then, run ‘git revert <commit_hash> –no-commit — <file_path>’. This reverts changes for the specified file without committing straight away. Same as with the “git checkout” method, you stage the reverted file and commit the change.
Alternatively, you can leverage backups, by using scripts or opting for a backup vendor such as GitProtect.io, which gives you the possibility of point-in-time restores and granular restores. The solution gives you the option to restore to different destinations, including your original organization, a new organization, and an on-prem device. Also, you can specify what you actually want to restore, like whole projects or just some metadata such as attachments.
How to undo the merge of a single file in git?
To undo the merge of a single file in git, run: ‘git reset HEAD~1 public/stylesheet/application.css’. This way you change the version of a file in the staged version to the version in ‘HEAD~1’, but your working copy stays unaltered.
Alternatively, you could check out first: ‘git checkout HEAD~1 — public/stylesheet/application.css’. This changes your working copy along with the staged version to the version from ‘HEAD~1. The ‘–’ is there as a security measure to avoid mistaking your file name with a commit. After that, you can amend your merge commit using: ‘git commit –amend’. This will effectively undo the merge of a single file in git, provided that you have not pushed the merge anywhere, as the merge will still just contain the changes from one of the branches.
Before you go:
✍️ Subscribe to GitProtect DevSecOps X-Ray Newsletter and stay current with the newest insights in DevSecOps
🔎 Check out 5 top arguments to start backing up DevOps tools as soon as possible
👀 Read our blog post Your own Git backup script vs. repository backup software, and see which backup option suits your needs
📅 Schedule a live custom demo and learn more about GitProtect backups to protect your source code on GitHub, Bitbucket, or GitLab
📌 Or try GitProtect backups for your GitLab, Bitbucket, GitHub, or Jira ecosystem to guarantee data protection and ensure continuous workflow