Git Time Machine
A Visual Guide to Undoing Things for Git Beginners
Fixing the Last Commit: --amend
When you commit too early, forget to add a file, or mess up the commit message… don’t worry, you can “fix” it!
The Flow: Replace, Don’t Just Repair
Flawed Commit:
Forgot to add forgotten_file
⬇️
Add Missing File:
git add forgotten_file
⬇️
Perfect Commit:
The old commit is replaced
Using the --amend
option, Git creates a brand new commit with the contents of your staging area and replaces your last “mistaken” commit with it.
1. Initial commit, but something is missing
git commit -m "initial commit"
2. Stage the forgotten file
git add forgotten_file
3. Re-commit using --amend
git commit --amend
Note
This opens your editor to change the commit message.
In the end, you only have one, perfect commit.
Danger
🚨 Important Warning!Never use
--amend
on a commit that has already been pushed to a remote repository (like GitHub)! This rewrites history and will cause major problems for your collaborators. This command is only for local commits you haven’t shared yet.
Understanding Git’s Three Core Areas
Working Directory
Where you actually modify files
⬇️
Staging Area
Files after git add
⬇️
Local Repository
History after git commit
The following operations are essentially about moving files between these three areas.
Unstaging a File: From Staging Area to Working Directory
When you use git add *
and accidentally stage a file you didn’t mean to, you need to pull it back from the staging area.
Staging Area
⬇️
Working Directory
The Modern Way (Git v2.23+)
git status
will directly tell you to use git restore
.
# Let's say you accidentally staged CONTRIBUTING.md
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
# Run the command it suggests
git restore --staged CONTRIBUTING.md
The Traditional Way
Older versions of Git will suggest using git reset
.
# Same situation, different suggestion
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
# Run the command it suggests
git reset HEAD CONTRIBUTING.md
Tip
💡 Result: The file `CONTRIBUTING.md` is now back to "modified but not staged." Your changes in the working directory are kept safe. This is a very safe operation.
Discarding Changes: From Repository to Working Directory
When you realize your changes to a file are completely wrong and want to revert it to how it was in the last commit…
Repository
(Last committed version)`checkout --' (Older Git) ❌