Session Ready
Exercise

How do I restore an old version of a file?

You previously saw how to use git checkout to undo the changes that you made since the last commit. This command can also be used to go back even further into a file's history and restore versions of that file from a commit. In this way, you can think of committing as saving your work, and checking out as loading that saved version.

The syntax for restoring an old version takes two arguments: the hash that identifies the version you want to restore, and the name of the file.

For example, if git log shows this:

commit ab8883e8a6bfa873d44616a0f356125dbaccd9ea
Author: Author: Rep Loop <[email protected]>
Date:   Thu Oct 19 09:37:48 2017 -0400

    Adding graph to show latest quarterly results.

commit 2242bd761bbeafb9fc82e33aa5dad966adfe5409
Author: Author: Rep Loop <[email protected]>
Date:   Thu Oct 16 09:17:37 2017 -0400

    Modifying the bibliography format.

then git checkout 2242bd report.txt would replace the current version of report.txt with the version that was committed on October 16. Notice that this is the same syntax that you used to undo the unstaged changes, except -- has been replaced by a hash.

Restoring a file doesn't erase any of the repository's history. Instead, the act of restoring the file is saved as another commit, because you might later want to undo your undoing.

One more thing: there's another feature of git log that will come in handy here. Passing - followed by a number restricts the output to that many commits. For example, git log -3 report.txt shows you the last three commits involving report.txt.

Instructions 1/4
undefined XP
  • 1

    The current contents of data/western.csv are shown in the terminal. Use git log -2 to list the last two changes to that file.

    • 2

      Use git checkout with the first few characters of a hash to restore the version of data/western.csv that has the commit message "Adding fresh data for southern and western regions.".

    • 3

      Use cat data/western.csv to display the updated contents.

    • 4

      Commit the restored version of data/western.csv, and be sure to include a message.