How to Undo the Last Git Commit

Undoing Git Commits: A Comprehensive Guide

In Git, it's common to make mistakes when committing changes. Fortunately, Git provides several ways to undo or modify your last commit. This guide will walk you through different scenarios and the appropriate commands to use.

1. Undo the last commit but keep the changes

If you want to undo the last commit but keep the changes in your working directory, use:

git reset HEAD~1

This command moves the HEAD and branch pointer back by one commit, effectively "uncommitting" the changes but leaving them staged.

2. Undo the last commit and discard the changes

To completely undo the last commit and discard all changes:

git reset --hard HEAD~1

Be cautious with this command as it permanently discards the changes.

3. Modify the last commit message

If you just need to change the commit message of the last commit:

git commit --amend

This opens your default editor where you can modify the commit message.

4. Add forgotten changes to the last commit

To add more changes to the last commit without creating a new commit:


git add forgotten_file
git commit --amend --no-edit
            

The --no-edit flag keeps the original commit message.

5. Undo a public commit

If you've already pushed the commit, it's better to create a new commit that reverts the changes:

git revert HEAD

This creates a new commit that undoes the changes from the last commit.

Conclusion

Understanding these Git commands allows you to maintain a clean and accurate commit history. Always be cautious when modifying history, especially in shared repositories, and communicate with your team when making significant changes to the commit history.