Undoing Things · practice
I Staged Something I Did Not Mean to Stage
You ran git add a little too broadly, and something is now staged that you do not want in your next
Those are two different wishes, and Git treats them as two different operations. This lesson is only the first one.
See what is staged
git status
scratch.tmp is a private scratch file, a couple of reminders to check tide times and ring the hostel. It is staged, which means it is queued for the next commit. It is not the sort of thing that belongs in a project’s history.
Take it back out of the staging area
git restore --staged scratch.tmp
git status
This is the same git restore from the previous lesson, with one option added. --staged tells it to change the staging area rather than the working tree. For a tracked file it restores the staged version from the newest commit. scratch.tmp has never been committed, so here that means removing it from the snapshot queued for the next commit.
After it runs, git status moves scratch.tmp from staged to untracked. It is still on disk, unchanged, with your two reminders in it. It is simply no longer on the list.
What this destroys, and what it cannot
Almost nothing, which is why it is worth learning early. git restore --staged undoes a decision, not an edit. Your file keeps its contents. Nothing is committed and no history moves.
The contrast with the previous lesson is the whole point, and it is worth holding on to:
git restore <file>changes the working tree. It throws away your edit.git restore --staged <file>changes the staging area. It keeps your file and only cancels the staging.
The option is the difference between the safe one and the final one. Read the command you are about to run.
Keeping it out for good
Unstaging fixes today. A scratch file you keep having to unstage is a sign you want Git to ignore it permanently, which is what a .gitignore file is for. That is Chapter 9, and it is a better answer than remembering every time.
notes.md has edits you want to keep, but you staged it too early. Which command takes it off the list for the next commit without touching your edits?
Next: the commit is already made, and it is wrong.