World map

 

BM: Baca dalam Bahasa Melayu

World 2: Undo Magic

Throw away a change

You will learn: how to throw away changes you don't want.

The problem

index.html wobbles in your working folder. It is marked changed. Your last commit sits safe in the repository.

You edited index.html and broke it. Ctrl+Z can’t go back that far. Now what?

Watch

The command git restore index.html types itself. The changed tag on index.html disappears. The file matches the last commit again.

git restore index.html puts the file back to its last saved version. This is called restore: Put a file back to a saved version..

Watch

git diff index.html shows the change you would lose: the Day 1 line became oops oops oops. Terminal output: $ git diff index.html diff --git a/index.html b/index.html index a8ad0de..eca16c6 100644 --- a/index.html +++ b/index.html @@ -1,2 +1,2 @@ <h1>My Diary</h1> -<p>Day 1: I learned Git.</p> +<p>oops oops oops</p>

⚠️ Danger: restore throws your changes away for good. Git never saved them, so there is no undo. Look first with git diff.

Try it

Throw away the broken index.html. Keep your style.css change.

Working folder
Staging area
  • Empty
Repository
  • 3 save points
  • Add style
  • Add day 1 page
  • Add README

Predict

Now you run git restore style.css. What happens to your teal heading?

Pick one answer.

Check

README.md is deleted, so ls does not list it. After git restore README.md, ls lists it again. Terminal output: $ rm README.md $ ls index.html style.css $ git restore README.md $ ls index.html README.md style.css

Deleted a saved file by mistake? git restore brings it back. It is in a commit, so Git still has it.

You did it!

You can now throw away changes you don’t want. Carefully!

Go deeper (optional)

git restore copies from the box. If you staged the file, you get the staged version. git restore . restores every tracked file. Old guides use git checkout -- index.html. It does the same job.

The old way: git checkout -- index.html also throws away the change to index.html. Terminal output: $ git status -s M index.html M style.css $ git checkout -- index.html $ git status -s M style.css