Lesson 1 of 6 in Undoing Things
Discarding and unstaging
Story: The Loose Cannon has been editing the plans again. Some of those edits have to go.
A file in a repository can have three versions at once:
- the one in the last commit,
HEAD: what you saved most recently; - the one in the index, also called the staging area: what your next commit will hold;
- the one in your working tree: the file you see and edit.
git add copies a file from your working tree into the index, and git commit records the index as a new commit. This Lesson goes the other way, with one command: git restore.
Unstaging: git restore --staged
Staged something by mistake? git restore --staged <file> copies the file from HEAD back into the index. The change is no longer staged, but your file keeps it, so nothing is lost.
If the file is new and was never committed, unstaging makes it untracked again. It stays on your disk.
Discarding: git restore
git restore <file> copies the file from the index over your working tree. Any change you haven't staged is overwritten.
This is the command in this Lesson that destroys work. An edit you never staged or committed isn't stored anywhere else, so git can't bring it back. Look at git status and git diff before you restore.
To throw away a staged change as well, unstage it first, then restore the file:
git restore --staged plan.txt
git restore plan.txt
The order matters. If you restore first, git copies the staged version into your file, which is the version you wanted to get rid of.
Let git status remind you
You don't need to memorise any of this. git status prints the right command above each list of files:
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
Both forms also take a folder: git restore . works on every file under the folder you're in.
Neither command makes a commit or moves a branch, so the Live Graph stays still. The changes happen in the index and in your files.
New commands
git restoregit restore --staged
Explainer: Restore puts a file back
Graph as text
project: your repo, you are here
- HEAD → main at b7f1723 "Write the plan"
Branches and tags
- main at b7f1723 "Write the plan"
Commits, newest first
- b7f1723 "Write the plan"; no parent; refs: HEAD → main
Challenge 1 of 3
Story: Someone scribbled on the plan. Put it back the way it was.
You changed plan.txt by mistake. Throw that change away, so the file matches your last commit again. Don't make a new commit.
Unlocks after Branching & Merging.
Terminal
Unlocks after Branching & Merging.
This Lesson can be played once Branching & Merging is complete. Its text and Explainer are open to everyone.