What is Git Amend?
git commit --amend lets you modify your most recent commit.
You can:
- Change the commit message
- Add or remove files
- Fix small mistakes
It replaces the last commit with a new one.
When to Use Git Amend
Use it to:
- Fix typos in the last commit message
- Add forgotten files
- Remove unwanted files
- Make small corrections
Note: Avoid amending commits that have already been pushed to a shared repository, as this rewrites history.
Change the Last Commit Message
To update the message without changing the content:
git commit --amend -m "New commit message"
Example:
git commit --amend -m "Fixed typo in commit message"
Add Files to the Last Commit
If you forgot to include a file:
git add <file>
git commit --amend
Example:
git add forgotten.txt
git commit --amend
Remove Files from the Last Commit
If you accidentally added a file:
git reset HEAD^ -- <file>
git commit --amend
Example:
git reset HEAD^ -- unwanted.txt
git commit --amend
Check the Commit History
After amending, see your commit log:
git log --oneline
Example output:
python-repl
07c5bc5 (HEAD -> master) Adding plines to reddme
9a9add8 (origin/master) Added .gitignore
81912ba Corrected spelling error
Fixing a Bad Commit Message Example
Suppose your log shows
07c5bc5 (HEAD -> master) Adding plines to reddme
You want to fix the spelling:
git commit --amend -m "Added lines to README.md"
Example output:
[master eaa69ce] Added lines to README.md
Date: Thu Apr 22 12:18:52 2021 +0200
1 file changed, 3 insertions(+), 1 deletion(-)
Check the log again:
git log --oneline
Updated log:
eaa69ce (HEAD -> master) Added lines to README.md
9a9add8 (origin/master) Added .gitignore
81912ba Corrected spelling error
Now the last commit is clean and correct!
Summary
Change last commit msg git commit --amend -m "New message"
Add file to last commit git add <file> → git commit --amend
Remove file git reset HEAD^ -- <file> → git commit --amend
View log git log --oneline
Git Amend Files
To add files when using --amend, follow the same process as before:
First, stage the files you want to include in the amended commit:
git add <file>
Then update the last commit with:
git commit --amend
This replaces the previous commit with a new one that includes your newly staged changes.