Mastering Git: How to Undo Your Most Recent Local Commits

Govinda Prakash
2 min readMay 16, 2023

Git has become an integral part of every developer’s workflow, offering an impressive set of features for version control. However, navigating its extensive functionality can sometimes be challenging, especially when it comes to correcting mistakes. One of the most common issues faced by developers is undoing recent commits. This guide will provide you with an in-depth understanding of how to reverse local commits in Git.

Whether you accidentally committed the wrong files or you wish to modify your last commit, Git provides multiple ways to undo these actions. Here, we will explore four different methods to reverse a commit:

Let’s assume you have a situation where ‘C’ is your HEAD and ‘F’ is the state of your files, represented as:

(F)
A-B-C

master

Option 1: git reset — hard

This option is suitable when you want to discard commit C entirely, along with any uncommitted changes. Run the following command:

git reset --hard HEAD~1

After this operation, your commit structure will look like:

(F)
A-B

master

B is now the HEAD, and because you used — hard, your files are reset to their state at commit B.

Option 2: git reset

If commit C isn’t entirely wrong but requires some tweaks, you can use git reset to undo the commit while preserving your changes for further editing. Use the following command:

perlCopy code
git reset HEAD~1

After running this command, the structure will appear like:

(F)
A-B-C

master

In both cases, HEAD is a pointer to the most recent commit. When you run git reset HEAD~1, you instruct Git to move the HEAD pointer back by one commit. However, unless you use — hard, your files remain unchanged.

Option 3: git reset — soft

If you want to undo your commit but leave your files and your index intact, use the — soft option:

git reset --soft HEAD~1

This command leaves your files and index untouched. When you run git status, you’ll see that the same files are in the index as before.

Option 4: Rescuing a destroyed commit

Suppose you have destroyed a commit using git reset — hard and later realize you need it back? Git has you covered:

git reflog

This command will display a list of partial commit hashes that you’ve navigated. Identify the commit you unintentionally destroyed, and run:

git checkout -b someNewBranchName shaYouDestroyed

This command resurrects the destroyed commit. Git does not permanently destroy commits for about 90 days, allowing you to retrieve commits you may have accidentally discarded.

In conclusion, Git provides several powerful features to undo local commits, enabling you to maintain a clean and accurate commit history. Understanding these commands enhances your version control and makes your coding process more efficient. However, remember to use these commands wisely to avoid unintentionally discarding important changes.

--

--