Ever committed and then realized you forgot a file or made a typo in the message?
Don't worry - git commit --amend lets you edit your most recent commit
without creating unnecessary clutter in your repository.
The Problem
We've all been there. You make a commit, feel satisfied, and then notice:
- You forgot to add a file
- There's a typo in your commit message
- You accidentally included a file you didn't want
Instead of making another commit just to fix these small issues, Git provides a cleaner solution.
The Solution: git commit --amend
The --amend flag allows you to modify your most recent commit. Here's how to use it:
Change the Commit Message Only
Command
git commit --amend -m "Your new commit message"
This will replace your last commit message with the new one you provide.
Add Forgotten Files
If you forgot to include a file in your commit:
Steps
1. Stage the forgotten file: git add forgotten-file.txt
2. Amend the commit: git commit --amend
This will add the staged file to your previous commit without creating a new one.
Remove Unintended Files
If you accidentally committed a file you didn't want:
Steps
1. Remove from staging: git rm --cached unwanted-file.txt
2. Amend the commit: git commit --amend
Important Safety Note
Amending is totally safe BEFORE pushing. It's NOT recommended in team workflows AFTER pushing, since it rewrites history.
Before Pushing
- Amending is completely safe
- No one else has your commits yet
- Feel free to amend as needed
After Pushing
- Amending rewrites history
- Other team members may have pulled your commits
- Creates conflicts for collaborators
- Better to create a new commit instead
Advanced Tips
For more advanced history management, you can also explore:
git rebase -i HEAD~n- Interactive rebase for editing multiple commitsgit push --force-with-lease- Safer force push that checks for upstream changes
Conclusion
git commit --amend is a simple but powerful tool for keeping your commit history clean.
Just remember: use it freely before pushing, but be cautious after your commits are shared with others.
Happy coding! Remember, a clean commit history makes everyone's life easier.