Three Ways to Role Back To A Previous Commit With Git
Nostalgic for a Previous Commit? Maybe You Messed Things Up?
So you messed everything up?
There are several ways to roll back to a previous commit in Git. Here are three common methods with examples for a zsh shell:
Using git checkout
git checkout
allows you to switch your working directory to the state of a specific commit. This command creates a detached HEAD state, which means that you are no longer on a branch, but you can create a new branch from this commit if needed.
Example:
git checkout <commit_hash>
# Replace <commit_hash> with the specific commit's hash you want to roll back to
Using git reset
git reset
moves the HEAD and the current branch pointer to a specified commit. There are three modes for git reset
: soft, mixed, and hard. The primary difference between these modes is how they handle changes in the working directory and the index.
Example:
git reset --hard <commit_hash>
# Replace <commit_hash> with the specific commit's hash you want to roll back to
--soft
: Preserves changes in the working directory and index, only moves the HEAD.
--mixed
(default): Preserves changes in the working directory, but resets the index. This mode allows you to re-commit or modify changes.
--hard
: Discards changes in the working directory and index, and moves the HEAD. This mode is destructive, as it completely removes all changes since the specified commit.
Using git revert
git revert
creates a new commit that undoes the changes made in a specific commit. This method is safer than git reset
, as it maintains the commit history.
Example:
git revert <commit_hash>
# Replace <commit_hash> with the specific commit's hash you want to undo
Remember to replace <commit_hash>
with the actual commit hash you want to roll back to. You can find the commit hash using git log
or any Git GUI client.