Undo file changes with git

Undo file changes with git

Intro

This information is based on issues I faced when making edits to my GitHub repository using GitPod cloud development environment. I wanted to write a quick article that will hopefully help others. This article assumes you are using git version 2.23 or newer, since that is when the restore command was introduced. You can check your version with git version.

First Steps

To check your current status to determine which instructions to follow, run git status and check the output. It will tell you if there have been any changes and whether or not those changes have been staged or committed.

Undo a change that hasn't been staged

If you've edited a file but haven't staged it yet using git add, you can use git restore filename.md to go back to the previous version.

Undo a change that has been staged

Once you git add a file, the changes will be staged, waiting to be committed. If you want to restore a staged file, use git restore --staged --workstree filename.md to un-stage the file and revert the changes to the file.

Undo changes after committing a file

Caution: The command presented in this step is going to destroy all changes to all files from your last commit. In my particular case, I used this because I had only edited one file, and I knew I did not need any of those changes, and I wanted it to go back to the version it was before.

If you've already committed a file, which means you've saved it to your local repository copy, but have not yet pushed it to the remote one (your GitHub repository), one way to revert that back is to use git reset --hard HEAD~. Please read This Page of the Pro Git book for a detailed explanation of this command. My explanation is that doing this is going to ignore your last commit, un-stage the files, and restore them to the last version. In other words, it will reverse your file edit, your git add and your git commit.

Closing

I hope you found this useful. If you have any requests for future posts, let me know in the comments!