During software development, you may sometimes need to undo commits or return to a previous commit. Accidentally pushed commits, faulty code, or temporary test changes can cause problems in a project. This is where the git reset command becomes useful.
In this article, we will look at how to return to a previous commit with Git reset, move the later changes into local changes (the working directory), and finally update the remote repository with force push.
What Is Git Reset?
git reset lets you move the HEAD pointer in a Git repository to a specific commit. With this command, you can:
- Return to the commit you want,
- Recover later commits as local changes,
- Reflect this operation in the remote repository when necessary.
Returning to a Previous Commit
To return to a previous commit, use the following command:
git reset <previous-commit-id>Here, <previous-commit-id> is the hash ID of the commit you want to return to.
For example:
git reset a1b2c3d4When this command runs:
- The project returns to the selected commit ID.
- The changes after that commit are moved into local changes.
In other words, the commits look as if they were removed, but your changes are not lost. They simply become uncommitted changes.
Moving Changes into Local Changes
If you do not use the --soft or --mixed options during git reset, Git uses mixed mode by default.
-
--soft: Only moves HEAD back; all changes remain staged. -
--mixed(default): Undoes the commits and moves the changes into local changes.
For example:
git reset --mixed <previous-commit-id>This way, your changes return to the working directory without being lost.
Updating the Remote Repository (Force Push)
After undoing commits locally, you may also want to update the commit history in the remote repository. For this, use force push:
git push --force⚠️ Warning:
Using --force changes the commit history in the remote repository. If you work with a team, this can cause problems in your teammates' repository copies. For that reason, git push --force-with-lease is a safer choice.
git push --force-with-leaseThis command deletes only the remote commits that match your local changes and helps prevent possible data loss.
Use Cases
- Undoing accidental commits.
- Cleaning up test commits.
- Creating a clean commit history in a project.
- Moving extra commits into local changes and editing them again.
Conclusion
Git reset is a powerful command for managing commit history and undoing faulty commits.
-
git reset <commit-id>returns to a previous commit. -
Changes are moved into local changes.
-
git push --forceupdates the remote repository.
If you want to clean up your commit history or get rid of incorrect commits, this method is very practical. However, if it is not used carefully, it can cause issues in team workflows.