Git by Example: Commit Amend
Learn how to modify your most recent commit. This is perfect for fixing typos in commit messages or adding forgotten files without creating a new commit.
Code
# 1. Commit with a typo
git commit -m "Fix bug in lgoin page"
# 2. Fix the typo in the message
git commit --amend -m "Fix bug in login page"
# Output:
# [main 2a3b4c] Fix bug in login page
# Date: Mon Oct 2 12:00:00 2023 -0700
# 1 file changed, 1 insertion(+)
# 3. Add a forgotten file to the last commit
git add forgotten-file.txt
git commit --amend --no-edit
# Output:
# [main 5d6e7f] Fix bug in login page
# Date: Mon Oct 2 12:05:00 2023 -0700
# 2 files changed, 2 insertions(+)Explanation
The git commit --amend command is a powerful tool that allows you to modify the most recent commit. Instead of creating a brand new commit to fix a small mistake—like a typo in the message or a forgotten file—you can "amend" the previous one. Git effectively replaces the old commit with a new one that contains your corrections.
It is important to understand that amending a commit rewrites history. The new commit will have a completely different SHA-1 hash than the original. This means the old commit is gone (replaced), and the new one takes its place.
Warning: Because this changes history, you should never amend a commit that you have already pushed to a shared remote repository. Doing so can cause significant problems for your teammates who may have already based their work on the original commit. Only amend commits that are still local to your machine.
- Modifies the most recent commit
- Useful for fixing typos or adding forgotten files
- Rewrites history (creates a new commit hash)
- Do not use on pushed commits
Code Breakdown
--no-edit flag tells Git to keep the existing commit message but include the newly staged files in the commit.
