0
0
Gitdevops~5 mins

Amending the last commit in Git - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you make a commit and realize you forgot to add a file or want to change the commit message. Amending the last commit lets you fix that without making a new commit.
When you forgot to include a file in your last commit and want to add it.
When you want to correct a typo or improve the message of your last commit.
When you want to combine small changes into the previous commit to keep history clean.
When you accidentally committed with the wrong message and want to fix it before pushing.
When you want to update the last commit with new changes before sharing your work.
Commands
Add the file 'example.txt' to the staging area so it will be included in the next commit.
Terminal
git add example.txt
Expected OutputExpected
No output (command runs silently)
Replace the last commit with a new one that includes the staged changes and updates the commit message to 'Fix typo in example.txt'.
Terminal
git commit --amend -m "Fix typo in example.txt"
Expected OutputExpected
[master 1a2b3c4] Fix typo in example.txt Date: Thu Jun 1 12:00:00 2024 +0000 1 file changed, 1 insertion(+), 1 deletion(-)
--amend - Replace the last commit with the new staged changes.
-m - Provide a new commit message inline.
Show the latest commit in a short format to verify the amended commit message and hash.
Terminal
git log -1 --oneline
Expected OutputExpected
1a2b3c4 Fix typo in example.txt
-1 - Show only the most recent commit.
--oneline - Display commit in a concise single line.
Key Concept

If you remember nothing else from this pattern, remember: git commit --amend lets you fix your last commit by adding changes or updating its message before pushing.

Common Mistakes
Running git commit --amend without staging any changes.
This only changes the commit message but does not add any new files or changes.
Stage the files you want to add with git add before running git commit --amend.
Amending a commit after it has been pushed to a shared repository.
This rewrites history and can cause problems for others who already pulled the original commit.
Only amend commits that have not been pushed yet, or coordinate with your team if you must rewrite history.
Forgetting to update the commit message when amending changes.
The old message remains, which might not reflect the new changes accurately.
Use the -m flag to provide a clear, updated commit message during amend.
Summary
Use git add to stage any new or changed files you want to include in the last commit.
Run git commit --amend -m "new message" to replace the last commit with your staged changes and update the message.
Verify the amended commit with git log -1 --oneline to ensure your changes and message are correct.