undo
git-commit
version-control
git

How do I undo the most recent local commits in Git?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Undoing a Commit and Redoing It

Scenario: You've made a commit with the message "Something terribly misguided" and need to undo this commit, make some changes, and then redo the commit.

Steps:

1. Undo the Last Commit:

bash
$ git reset HEAD~

This command will undo the last commit, but it will leave your working tree (the state of your files on disk) untouched. This means your changes will still be there, just not committed.

2. Make Corrections to Your Files: Edit your files as necessary to correct the issue.

3. Stage the Changes:

bash
$ git add.

Stage the files that you want to include in your new commit.

4. Commit the Changes:

bash
$ git commit - c ORIG_HEAD

This command will commit the changes, reusing the old commit message. The reset command copied the old HEAD to .git/ORIG_HEAD, and commit -c ORIG_HEAD will open an editor with the log message from the old commit, allowing you to edit it if necessary. If you do not need to edit the message, you can use the -C option instead.

Important Notes:

  • git reset is the command responsible for undoing the commit.
  • reset leaves your working tree untouched.
  • commit -c ORIG_HEAD allows you to reuse and edit the old commit message.
  • commit -C ORIG_HEAD allows you to reuse the old commit message without editing.

Alternative: Amend the Previous Commit

If you only need to make minor changes or correct the commit message of the last commit, you can use git commit --amend.

Command:

bash
$ git commit --amend

This command will open an editor allowing you to amend the previous commit. You can add changes within the current index to the previous commit or edit the commit message.

Removing a Pushed Commit

If the commit has already been pushed to a remote repository, you need to rewrite history. This can be done using git push --force or preferably git push --force-with-lease.

Command:

bash
$ git push origin main--force -with-lease
  • Warning: Rewriting history is dangerous, especially if others are working on the same branch. Always prefer --force-with-lease over --force.

Further Reading:

  • Git Reflog: Use git reflog to determine the SHA-1 for the commit to which you wish to revert.
  • HEAD Reference: HEAD~ is the same as HEAD~1. For more details on HEAD, refer to What is the HEAD in Git?.

Example Workflow:

  • Accidental Commit: git commit -m "Something terribly misguided"
  • Undo the Commit: git reset HEAD~
  • Make Corrections: Edit files as necessary.
  • Stage Changes: git add .
  • Reuse and Edit Commit Message: git commit -c ORIG_HEAD

By following these steps, you can effectively undo and redo a commit in Git, ensuring your history remains clean and accurate.


Course illustration
Course illustration

All Rights Reserved.