How to Undo the Most Recent Local Commits in Git

When working with Git, it’s common to make local commits that later need to be modified or removed. Whether it’s to correct a mistake, clean up your commit history, or revise staged changes, Git provides several ways to undo recent commits safely. This guide explains how to undo the most recent local commits using standard Git commands.

Prerequisites
Ensure that you have Git installed and are operating within a Git repository. You can check your current repository status with:

git status

1. Viewing Recent Commits
Before undoing a commit, it’s often helpful to view your commit history:

git log --oneline

This will show a concise list of recent commits, each with a unique commit hash.

  1. Undo the Most Recent Commit (Preserve Changes)
    To undo the most recent commit but keep your changes staged (in the index), use:
git reset --soft HEAD~1

  • –soft: Removes the commit but retains all staged changes.

  • HEAD~1: Refers to the commit before the most recent one.

This is useful when you want to revise the previous commit message or combine changes into a new commit.

3. Undo the Most Recent Commit (Unstage Changes)

If you want to undo the commit and unstage the changes (keep them in your working directory), use:

git reset --mixed HEAD~1

This will:

  • Remove the last commit.

  • Unstage the files but keep changes in the working directory.

4. Undo the Most Recent Commit (Discard Changes)
To completely remove the most recent commit and discard all associated changes:

git reset --hard HEAD~1

⚠️ Warning: This will permanently delete the commit and any uncommitted changes. Use this only if you are sure the changes are no longer needed.

5. Undo Multiple Commits
You can undo multiple commits by changing HEAD~1 to HEAD~n, where n is the number of commits to undo. For example:

git reset --soft HEAD~3

This undoes the last 3 commits while preserving changes in the staging area.

6. Best Practices

  • Use –soft or –mixed for reversible changes.

  • Use –hard only when you are certain the data can be discarded.

  • Always review the current state with git status and git log before performing a reset.

  • If you’ve already pushed commits to a remote, consider using git revert or force pushing with caution (git push –force), especially when collaborating with others.

By choosing the appropriate reset option, you can effectively manage and clean your local Git history before pushing changes to a shared repository.

LinkedIn Account : LinkedIn
Twitter Account: Twitter
Credit: Graphics sourced from LinuxTech

Leave a Reply