0
0
GitHow-ToBeginner · 3 min read

How to Amend Last Commit in Git: Simple Guide

Use the git commit --amend command to modify the last commit in Git. This lets you change the commit message or add new changes to the previous commit without creating a new one.
📐

Syntax

The basic syntax to amend the last commit is:

  • git commit --amend: Opens your default editor to change the last commit message.
  • git commit --amend -m "new message": Directly replaces the last commit message without opening an editor.
  • Before amending, you can stage new changes with git add to include them in the amended commit.
bash
git add <file>
git commit --amend -m "Updated commit message"
💻

Example

This example shows how to change the last commit message and add a new file to it.

bash
echo "Hello" > file1.txt
git add file1.txt
git commit -m "Initial commit"

echo "More content" > file2.txt
git add file2.txt
git commit --amend -m "Initial commit with two files"
Output
[master (root-commit) 1a2b3c4] Initial commit 1 file changed, 1 insertion(+) create mode 100644 file1.txt [master 5d6e7f8] Initial commit with two files 1 file changed, 1 insertion(+) create mode 100644 file2.txt
⚠️

Common Pitfalls

1. Amending pushed commits: If you amend a commit that has already been pushed to a shared repository, you must force push with git push --force. This can overwrite history and confuse collaborators.

2. Forgetting to stage changes: If you run git commit --amend without staging new changes, only the commit message will change, not the content.

3. Using amend for multiple commits: git commit --amend only changes the last commit. To change older commits, use git rebase -i.

bash
git commit --amend
# Without staging changes, only message changes

git add newfile.txt
git commit --amend
# Now content and message update
📊

Quick Reference

Here is a quick summary of commands to amend the last commit:

CommandDescription
git commit --amendEdit last commit message in editor
git commit --amend -m "message"Change last commit message directly
git add Stage changes to include in amended commit
git push --forceForce push amended commit to remote (use carefully)

Key Takeaways

Use git commit --amend to modify the last commit message or content.
Stage any new changes before amending to include them in the commit.
Avoid amending commits already pushed unless you force push carefully.
Amend only affects the last commit; use interactive rebase for older commits.
Always double-check before force pushing amended commits to shared repos.