Skip to content

Ammending Changes on a Commit

Understanding how to amend changes on a commit in Git is important for keeping your project history clean and accurate. Here’s a simple guide on how to do it.
Definition
Amending a commit in Git allows you to modify the most recent commit by adding new changes or correcting mistakes without creating a new commit. This feature helps maintain a clean and concise project history.
Sample Example
Sometimes, after making a commit, you might notice you forgot something or made a mistake. Instead of making a new commit, you can fix the previous one.
Let’s say you have a file called example.txt and you made a commit but forgot to include a line of text.
Create and Commit the File
Create the file using the redirecting command.
echo "This is a sample text file." > example.txt
Add the file to the staging area.
git add example.txt
Commit the file.
git commit -m "Initial commit with example.txt"
Realize a Mistake:
You realize you forgot to add another line to example.txt.
Make Your Changes:
Open example.txt and add the missing line.
echo "This is an additional line." >> example.txt
Stage Your Changes:
Add the changes to the staging area.
git add example.txt
Amend the Commit:
If you use git commit here, a new commit will be created. This will add the new changes as a separate commit, which can clutter your commit history and make it less clear.
To amend the previous commit to include the new changes, use:
git commit --amend --no-edit
By using --no-edit, the commit message remains the same.
Conclusion
By following these steps, you can amend your previous commit to include any forgotten changes, keeping your commit history clean and accurate. Amending commits is a powerful feature in Git that helps you maintain a tidy and professional project repository.
Want to print your doc?
This is not the way.
Try clicking the ··· in the right corner or using a keyboard shortcut (
CtrlP
) instead.