Day 12: Mastering Git Rollback
Oct 23, 2024
•10:16 PM GMT+8

Our journey with Git will be more successful if we are able to undo changes. There are several ways to roll back changes in Git, such as reverting a specific file or undoing entire commits. In this post, we will cover Git rollback techniques, such as reverting files and resetting commits.
Tasks
Revert a file: git checkout
and git restore
When you need to undo changes in a specific file, Git provides two primary commands: git checkout
and git restore
.
Using git checkout
:
git checkout SAMPLE.MD
This command discards local changes in SAMPLE.MD
and reverts it to its last committed state. It's useful for when you want to undo edits to a file without affecting the rest of your working directory.
Using git restore
:
git restore SAMPLE.MD
This is a newer command introduced to simplify rollback processes. It serves the same purpose as git checkout
but is more intuitive for specific file restores. Use this to reset changes in SAMPLE.MD
to its last committed state.
Soft Reset
A soft reset allows us to undo a commit while keeping the changes staged for further modification. This is helpful when we need to adjust a commit without losing work.
git reset --soft <commit-hash>
This command <commit-hash>
specific commit, the changes remain staged, ready for you to recommit.

Hard Reset
A hard reset is a more destructive action that removes the commit and discards all local changes. Use this when you want to wipe the slate clean and reset everything to a previous commit.
git reset --hard <commit-hash>
This will reset your working directory and staging area to match the previous commit, erasing all uncommitted changes.

Revert a Specific Commit
The git revert command can be used to undo a specific commit while maintaining the commit history. It does not rewrite history, but creates a new commit that undoes the changes introduced by the specified commit.
git revert <commit-hash>
Discard Local Changes and Revert to the Last Commit
This command will delete all uncommitted changes and revert your working directory to the state it was before the last commit.
git checkout .
Wrapping Up
Managing your code efficiently requires a thorough understanding of these Git rollback commands. No matter how minor or major your changes are, these techniques will help you maintain a clean repository and avoid errors. Our next post will cover some Git cheat codes, providing quick shortcuts to everyday commands.
Day 12: Mastering Git Rollback
Discover how to undo changes easily using soft reset, hard reset, reverting specific commits, and discarding local changes with Git rollbacks.
For the passion of automated cloud solutions.
Subscribe to get the latest posts. I mostly write about Backend (Python/Bash), DevOps and Linux.