Lesson 3: Read history and recover a file
Lesson objectives:
- Read the commit history with
git log.- Identify a commit by its hash.
- Recover an earlier version of a file using
git restore.Prerequisites: Lessons 01-02 (save points,
git init,git add,git commit) | Previous << 02 | Next 04 >>
What if you liked yesterday's version better?
You have made a commit. Then you edited the file again. Now you realize the new version is worse. You want the old version back.
Git stores every commit forever. Each commit has a unique hash — a long string of letters and numbers that acts as its ID. You can see the list of commits with git log 1. Once you know the hash of the commit you want, you can ask Git to restore a file to the way it looked at that commit.
Reading the timeline
Run git log in your git-practice folder. You will see something like this:
The long string after commit is the hash. You do not need to type the whole thing; the first few characters are usually enough if they are unique.
git log shows the commits in order, newest first. The top commit is the one you are currently looking at.
Recovering an older version
The command git restore --source=<hash> <file> replaces the current file with the version from that commit. The most common source is HEAD, which means "the current commit," or HEAD~1, which means "one commit before the current one" 2.
After running this, open draft.txt in your text editor. It should show the older version.
A safety note: git restore changes the file in your working directory. If you have uncommitted changes you care about, commit them first or make a copy outside the repository.
Worked example (follow along)
Stay in your git-practice folder.
If git log --oneline shows only one commit, HEAD~1 does not exist yet. Make two commits in Lesson 2 first, or create a second commit now before trying this step.
Your turn (faded example)
Fill in the command that recovers the version of notes.txt from two commits ago.
Answer:
Common mistake breakdown
Mistake: Running git restore --source=HEAD~1 file.txt and thinking you changed the past. You did not. You only copied an old version into your working directory. The original commit is still in the history. If you want to keep the restored version, you must stage and commit it again.
Summary + what's next
You can now read the history of a repository and recover an earlier version of a file. That is two of the four core skills. Next, you will learn how to experiment safely using branches.
Footnotes
-
Pro Git, Recording Changes to the Repository — https://git-scm.com/book/en/v2/Git-Basics-Recording-Changes-to-the-Repository ↩
-
Git User Manual — https://git.github.io/htmldocs/user-manual.html ↩