Master Git: Undo Unadded Changes, Revert Commits, and Recover Files
Learn how Git tracks modifications instead of files, and discover step‑by‑step techniques to discard unadded changes, revert staged edits, delete files, and restore removed or altered files using commands like git checkout, git reset, git rm, and git reflog, with practical examples and screenshots.
Why Git tracks modifications, not files
Git records each change (addition, deletion, or edit of lines) as a modification. Creating a new file is also a modification. Commits contain the set of staged modifications, not whole files.
Experiment: committing only the first modification
Append a line to readme.txt and view it with cat.
Stage the change: git add readme.txt.
Modify the file again without staging.
Commit: git commit -m "first change".
Only the first modification is included because the second change was never added to the index.
To see the uncommitted change: git diff HEAD -- readme.txt.
Committing the second modification
Run git add readme.txt again, then git commit.
Or stage the second change first and then commit, which combines both modifications into a single commit.
Discarding unadded changes
To throw away modifications that have not been staged: git checkout -- readme.txt The double‑dash -- separates the file name from a possible branch name.
Discarding staged changes
If a file is already in the index but you want to discard the change: git reset HEAD readme.txt # unstage git checkout -- readme.txt # restore the file to the last committed version
Deleting a file
File deletion is also a modification. After removing the file from the working directory, run: git rm test.txt Commit the deletion; git status will show the removed file.
Recovering a deleted file
If the file was previously committed, restore it with: git checkout -- test.txt This replaces the working‑directory version with the last committed version. Files never added to the repository cannot be recovered.
Viewing reference history
Use git reflog to list all reference updates, which helps locate previous commits for recovery.
Additional notes
When a file is both modified and staged, git reset HEAD <file> removes it from the index while keeping the changes in the working directory. Afterward you can either commit the changes or discard them with git checkout -- <file>.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
ITPUB
Official ITPUB account sharing technical insights, community news, and exciting events.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
