Skip to content
Middle–Senior252 viewsAsked at 2 companies

How to revert the last two commits but keep their changes?

Practice

AI answer

In Git, there are several commands to undo changes depending on the situation:

  • git checkout -- <file> — undo changes in the working directory for a specific file, reverting it to the last commit state.
  • git reset HEAD <file> — remove the file from the index (staging area), but keep the changes in the working directory.
  • git reset --hard — revert all changes in the working directory and index to the last commit (all unsaved changes will be lost).
  • git revert <commit> — create a new commit that undoes the changes of the specified commit.

Example of undoing all local changes:

git reset --hard

Be cautious with this command, as it permanently deletes unsaved changes.