Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
git

How to undo commits in Git

Programming Bytes

You may get into a situation where you want to undo one of your commits on Git. You may wish to:

  • undo the last commit
  • undo multiple commits

Undo the last commit

git rest will take you back to the specified commit in your current branch. To undo one commit on the current HEAD, we can use HEAD~1 with git reset:

git reset --soft HEAD~1

The above code will undo the commit. With the --soft flag the changes made on that commit will be available in the staging area so the user will not lose the changes.

If you don’t want to keep these changes of the commit in the staging area, then use the --hard flag:

git reset --hard HEAD~1

The 1 in HEAD~1 can be replaced with any positive integer. If it is, it will undo n commits.

Undo multiple commits

First, print the list of the commits on the current branch:

git reflog show HEAD

// the code will print something like this
849b15d67 files added
340b94da7 issue  fix
140b32d6c function added
...
// press q to stop 🛑 printing logs 

If we want to undo commits before 140b32d6c, type the following:

$ git reset --soft 140b32d6c

This will take you to the 140b32d6c commit and the changes done will be stored in the staging area. If you don’t need those changes, use the --hard flag instead of the --soft flag.

To log only the first 10 commits, we can add -10 to the reflog command — git reflog show HEAD -10.

RELATED TAGS

communitycreator
git
RELATED COURSES

View all Courses

Keep Exploring