0
0
GitHow-ToBeginner · 4 min read

How to Use Git Commit Amend to Modify Last Commit

Use git commit --amend to modify the last commit. This lets you change the commit message or add new changes before pushing to the remote repository.
📐

Syntax

The basic syntax for amending the last commit is:

  • git commit --amend: Opens the editor to change the last commit message.
  • git commit --amend -m "new message": Directly replaces the last commit message without opening an editor.
  • git add <files> before amending: Adds new changes to the last commit.
bash
git add <files>
git commit --amend -m "new commit message"
💻

Example

This example shows how to fix a typo in the last commit message and add a new file to the same commit.

bash
echo "Initial content" > file.txt

# Stage the file
 git add file.txt

# Commit with a message
 git commit -m "Initail commit"

# Fix the typo in the commit message
 git commit --amend -m "Initial commit"

# Add another file
 echo "More content" > file2.txt
 git add file2.txt

# Amend the last commit to include the new file
 git commit --amend --no-edit
Output
On branch main Your branch is up to date with 'origin/main'. Changes to be committed: (use "git reset HEAD <file>..." to unstage) new file: file.txt [main 1a2b3c4] Initial commit Date: Thu Apr 27 12:00:00 2024 +0000 [main 5d6e7f8] Initial commit Date: Thu Apr 27 12:05:00 2024 +0000 [main 9a0b1c2] Initial commit Date: Thu Apr 27 12:10:00 2024 +0000
⚠️

Common Pitfalls

Common mistakes when using git commit --amend include:

  • Amending commits that are already pushed to a shared remote, which can cause conflicts for others.
  • Forgetting to stage new changes before amending, so the commit does not include them.
  • Using amend to fix commits far back in history instead of the last one.

Always check if the commit is pushed before amending.

bash
git commit --amend -m "Fixed message"
# Wrong: no new changes staged, so commit content stays the same

# Correct:
git add changed_file.txt
git commit --amend --no-edit
📊

Quick Reference

CommandDescription
git commit --amendEdit last commit message in editor
git commit --amend -m "message"Replace last commit message directly
git add + git commit --amendAdd new changes to last commit
git commit --amend --no-editAdd changes without changing message

Key Takeaways

Use git commit --amend to change the last commit message or add new changes.
Always stage new changes with git add before amending to include them.
Avoid amending commits that are already pushed to shared repositories.
Use --no-edit to keep the existing commit message when adding changes.
Amend only the most recent commit; use other tools for older commits.