Git is the most popular version control system to efficiently manage your (web) development projects.
In addition to saving changes and tracking code progress, there are times when you may want to undo changes made to your code.
Undoing changes is typically required to undo:
Unstaged changes (changes made to the working tree since the last commit)
Staged changes (changes made to the working tree and added to the staging area / index)
git restore and
git reset you can easily bring your projects back on track:
Undo Unstaged Changes
You made changes to a file, saved the file and decide that you don't want to keep these changes.
git restore will restore the file to the last committed version, effectively undoing any changes that have been made since then.
The file has to be part of an earlier commit, "restore" does not work for newly created files since the last commit.
You can either restore an individual files with
git restore <filename>
(<filename> is the name of the file that should be restored)
all project files containing untracked changes with:
git restore .
Undo Staged Changes
In addition to the "unstaged changes" scenario, you now also added the updated project state (single or multiple files) to the staging area / the index, e.g. with
git add .
Undoing such staged changes requires two steps:
Unstaging the changes with
git reset <filename>
(<filename> is again the name of the file that contains staged changes, with
. you can also unstage changes for all project files containing staged changes).
Undoing unstaged changes and therefore removing the newly added code with
git restore as explained above.
In addition to resetting single or multiple project files, we can also reset the entire repository to a previous state.
After adding changes to the project and storing these in a new commit, we want to revert these changes and jump back to an earlier state / commit of our project. The newly created commit should be deleted, so the HEAD of your project will be reset.
In command form we add this action to the
git reset command, starting from the latest and newly created commit.
git reset HEAD~1will reset the HEAD of our project by one commit
git reset HEAD~2will reset our project by two commits
You get the idea...
After resetting the HEAD, file changes are still kept as unstaged changes, these can be removed with
git restore . .
Using a hard reset will combine these two steps:
git reset --hard HEAD~1 will reset the project by one commit and also delete any changes added to the project since the last commit.