Sometimes you need to modify commit history to keep your project clean and organized.
Git provides powerful tools for editing, reordering, and temporarily saving changes.
In this chapter, we cover three important techniques: amend, rebase, and stash.
1. Using git commit --amend
The amend command lets you modify the most recent commit.
You can use it to fix commit messages or include forgotten changes.
Fixing a commit message
git commit --amend -m "New and improved commit message"Adding missing changes to the last commit
Stage your changes:
git add filename.jsThen amend:
git commit --amendThis replaces the previous commit with a new one.
Important: Never amend commits that were already pushed to a shared remote repository.
It rewrites history and can cause problems for teammates.
2. Using git rebase (Interactive Rebase)
Rebase allows you to clean up your commit history by editing, deleting, or reordering commits.
Interactive rebase is especially powerful for maintaining a clean project history.
Start an interactive rebase for the last 3 commits
git rebase -i HEAD~3Git will open an editor showing something like:
pick 1a2b3c4 Add login form
pick 5d6e7f8 Fix login CSS
pick 9f0a1b2 Update API endpointYou can replace "pick" with commands like:
- pick = keep the commit
- reword = change commit message
- edit = modify commit content
- squash = combine commits
- drop = delete commit
Example: squashing commits
Change:
pick 1a2b3c4 Add login form
pick 5d6e7f8 Fix login CSSTo:
pick 1a2b3c4 Add login form
squash 5d6e7f8 Fix login CSSRebase produces a single clean commit.
Completing the rebase
If Git pauses during rebase, continue with:
git rebase --continueAbort the rebase and return to original state:
git rebase --abort3. Using git stash
Sometimes you need to switch branches but you're not ready to commit your work.
Stash lets you save changes temporarily without committing them.
Stash your current work
git stashOr include untracked files:
git stash -uView stash list
git stash listExample output:
stash@{0}: WIP on feature/cart
stash@{1}: WIP on mainApply the latest stash
git stash applyApply and remove stash
git stash popRemove stashes manually
git stash drop stash@{0}Remove all stashes:
git stash clearWhen To Use Each Tool
Amend
- Fix small mistakes
- Add missing files
- Update commit messages
- Only safe before pushing
Rebase
- Clean up messy history
- Combine or reorder commits
- Rewrite commit messages
- Not recommended for shared public history
Stash
- Save temporary work
- Switch branches safely
- Recover WIP later
Summary
In this chapter, you learned:
- How to modify your latest commit using
amend - How to rewrite and organize commit history using
rebase - How to save temporary work using
stash - When to use each history-rewriting tool
These tools help keep your repository history clean, readable, and professional.
Next, we explore helpful Git aliases and best practices to improve your daily workflow.