DEV Community

Ankit Verma
Ankit Verma

Posted on

How to Undo the Most Recent Local Commits in Git

Git makes it easy to undo your most recent local commits (commits that haven’t been pushed yet). Below are the safest and most common ways to do it.


1. Undo the Last Commit (Keep Changes Staged)

If you want to undo the last commit but keep your changes staged:

git reset --soft HEAD~1
Enter fullscreen mode Exit fullscreen mode

2. Undo the Last Commit (Keep Changes Unstaged)

To undo the commit but keep the changes in your working directory:

git reset --mixed HEAD~1
Enter fullscreen mode Exit fullscreen mode

or simply:

git reset HEAD~1
Enter fullscreen mode Exit fullscreen mode

3. Completely Remove the Last Commit

If you want to remove the commit and discard all changes:

git reset --hard HEAD~1
Enter fullscreen mode Exit fullscreen mode

⚠️ This permanently deletes your changes.

Use only when you are absolutely sure.


4. Undo Multiple Local Commits

To undo the last N commits, replace N with the number of commits:

git reset --soft HEAD~N
Enter fullscreen mode Exit fullscreen mode

Example (undo last 3 commits):

git reset --soft HEAD~3
Enter fullscreen mode Exit fullscreen mode

Use these commands only for local commits.

If the commit is already pushed to a remote repository, prefer git revert to avoid breaking shared history.

Top comments (0)