Git: How to “undo”
-
What we’ll cover
Undoing a commit using `git revert`
Undoing a commit using `git reset`
Using `git reset` on uncommitted code
-
Undoing committed code
Reverting a commit in Git means creating a new commit that undoes the changes introduced by a previous commit. There are several ways to achieve this, depending on your specific use case. Here we’ll discuss a couple of common methods: revert and reset.
-
Undoing committed code: git revert
- Identify the commit you want to revert.
(You can do this by usinggit logto view the commit history and find the commit hash of the one you want to undo.) -Undoing committed code: git revert
- Use the
git revertcommand followed by the commit hash of the commit you want to revert:git revert <commit-hash>(Replace
<commit-hash>with the actual hash of the commit you want to revert.) -Undoing committed code: git revert
-
Git will open your default text editor to create a commit message for the “revert” commit. You can modify the message if needed.
- Save and close the text editor. Git will create a new commit that undoing the changes made by the specified commit.
-
Undoing committed code: git revert
Push the changes to your remote repository if necessary:
git push <remote_alias> <branch_name>
- The git revert command is a safe way to revert changes because it creates a new commit that undoes the previous one while preserving the commit history. -
Undoing committed code: git reset
(Use with Caution!)
You can also use git reset to revert a commit, but be cautious when doing this, as it can rewrite history and potentially lose commits.
-
Undoing committed code: git reset
-
Identify the commit you want to revert and its parent commit (the commit before it) using git log.
-
Use
git resetto move the branch pointer back to the parent commit while preserving the changes in your working directory:git reset <parent-commit-hash>(Replace
<parent-commit-hash>with the hash of the parent commit.)
-
Undoing committed code: git reset
- Commit the changes to create a new commit. This effectively “reverts” the changes introduced by the commit you wanted to undo.
-
Undoing committed code: git reset
- Force push the changes to the remote repository if necessary, as you’ve rewritten history:
git push --forceReverting commits using git reset can be risky, especially in a shared repository, as it can create confusion for other contributors. It’s generally safer to use git revert to create a new commit that undoes the changes while preserving the commit history.
-
how to use git reset safely:
The safest use case git reset, is to undo changes that you haven’t yet committed to the repository.
- To revert to your currently committed codebase, use the flag
--hard:
git reset --hard
This will return your codebase to the most recent commit.
-
Recap
- To undo changes you’ve already committed, it is safest to use
git revert. - To undo uncommitted changes, use
git reset.
-
