Skip to content
Programming contents

Lesson 2.5.3: History and going back

What you save with Git can be looked at and recovered: the history, the changes and any earlier version.

The idea

Saving versions only helps if you can look at them and get them back. Three commands:

  • git log: the list of commits.
  • git diff: what you've changed since the last one.
  • git restore: going back.

The history

Terminal
git log --oneline
Terminal
7b1e0d4 (HEAD -> main) Add the 3 times table
3f2a1c9 Add the greeting
  • Each commit has an identifier: 7b1e0d4.
  • The most recent is at the top.
  • HEAD marks where you are.

If the list doesn't fit, Git shows it page by page: the q key gets you out.

What you've changed

Change the text in hello.js to "Goodbye from a file", save, and:

Terminal
git diff
Terminal
diff --git a/hello.js b/hello.js
index 5c1b2a3..8d4e6f1 100644
--- a/hello.js
+++ b/hello.js
@@ -1 +1 @@
-console.log("Hello from a file");
+console.log("Goodbye from a file");

What matters are the last lines: with -, what goes out; with +, what comes in.

Undoing what you haven't saved

Terminal
git restore hello.js

The file goes back to how it was in the last commit.

Careful: whatever wasn't in a commit is lost, and this can't be undone.

Getting an old version back

With a commit's identifier, bring the file back as it was then:

Terminal
git restore --source=3f2a1c9 hello.js

The file changes in your folder. If you want to keep that version, make a commit.

Try it

Exercise

Delete everything in table.js and save. Look at the change with git diff and get the file back.

Show the solution
Terminal
git diff
git restore table.js
git status

git diff shows every line with -. After git restore, git status says nothing to commit again.

Summary

  • git log --oneline shows the history; each commit has an identifier.
  • git diff shows what changed: - out, + in.
  • git restore file throws away unsaved changes, for good.
  • git restore --source=id file brings back an old version.