Rewrite Commit
What Will We Learn?
We’ll learn how to use git commit --amend to fix commit messages and forgotten files, along with best practices and precautions before amending pushed commits.
How to Rewrite Commit
git commit --amend lets you modify the most recent commit instead of creating a new one. Useful for fixing typos, forgotten files, or improving commit messages before pushing.
Amend Flow
flowchart TD
A[Last Commit] --> B{Need to fix?}
B -->|Message typo| C[git commit --amend -m new_message]
B -->|Missing file| D[git add file + git commit --amend --no-edit]
C --> E[New commit replaces old one]
D --> E
Common Use Cases
Fix a typo in the last commit message
git commit --amend -m "fix: correct null pointer exception in auth service"Add a forgotten file to the last commit
git add forgotten_file.js
git commit --amend --no-edit
--no-editkeeps the original commit message unchanged.
Update both code and message
git add .
git commit --amend -m "feat: add input validation for user registration form"Important Warning
Warning
Never amend a commit that has already been pushed and shared with others — it rewrites commit history (changes the commit hash), which can cause conflicts for teammates.
If you must amend a pushed commit:
git push --force-with-lease--force-with-lease is safer than --force since it fails if someone else pushed new changes.
Last updated on