Lesson 3 - Reviewing History
Every commit you make is a save point. In this module you’ll read the log of those save points, visit an older version of your project, and throw away changes you no longer want. The sandbox starts with the four commits from the previous modules, including the title change you made in the last exercise.
Reading the Log
Git records a log entry every time you commit. Use git log to view it:
git logEach commit has a long hash that uniquely identifies it. You’ll also see the author, the date, and the commit message. The most recent commit appears first.
The --oneline option gives you a brief summary:
git log --onelineEach line shows a shortened hash and the commit message. You can use either the short or the long hash to refer to a commit.
Going Back in Time
You can revisit any save point by checking out that commit. Your hashes won’t match the ones in this course, so this example uses HEAD~3 to refer to the commit three steps before the latest one. HEAD is Git’s name for the commit you’re looking at right now.
Look at the file before you time travel:
cat index.htmlNow switch to the commit from before you added the paragraphs:
git switch --detach HEAD~3Git warns that you’re in a “detached HEAD” state. That means you’re looking at an old snapshot rather than the tip of a branch. You can look around, and you can even make experimental commits, but they won’t belong to main unless you create a branch for them.
Look at the file now:
cat index.htmlThe paragraphs disappeared. That’s because you’re looking at an old snapshot of the code. The paragraphs still exist in later commits.
Go back to the current state of the repository by switching to main:
git switch main
cat index.htmlThe paragraphs are back.
Throwing Work Away
Sometimes you make a change and decide you don’t want it. Add a fourth paragraph:
sed -i 's| </body>| <p>This is the fourth paragraph.</p>\n </body>|' index.html
git statusThe status shows the file changed. Use git diff to see what you changed. This is a great way to find the code you added that broke things since your last commit:
git diffIf you decide you don’t want that change, restore the file from the last commit. The status output already told you the command:
git restore index.html
git statusThere’s nothing left to do. Git discarded the change and the file matches the last commit again.
Your Turn
Look at the one-line log, then switch to the first commit using HEAD~3 and show the file. Finally, switch back to main:
git log --oneline
git switch --detach HEAD~3
cat index.html
git switch mainWhat You Learned
git logshows the history of commitsgit log --onelinegives a brief summary of each commitgit switch --detachlets you look at an old commitgit switch mainreturns you to the latest commit on the main branchgit restorethrows away changes you haven’t committed
In the next module you’ll add more files to the repository.