Getting Old Versions

Goals

  • Learn how to checkout any previous snapshot into the working directory.

Going back in history is very easy. The checkout command will copy any snapshot from the repository to the working directory.

Get the hashes for previous versions

Execute:

  1. git hist

Note: You did remember to define hist in your .gitconfig file, right? If not, review the lab on aliases.

Output:

  1. $ git hist
  2. * 4254c94 2020-06-20 | Added a comment (HEAD -> master) [Jim Weirich]
  3. * c8b3af1 2020-06-20 | Added a default value [Jim Weirich]
  4. * 30c2cd4 2020-06-20 | Using ARGV [Jim Weirich]
  5. * 4445720 2020-06-20 | First Commit [Jim Weirich]

Examine the log output and find the hash for the first commit. It should be the last line of the git hist output. Use that hash code (the first 7 characters are enough) in the command below. Then check the contents of the hello.rb file.

Execute:

  1. git checkout <hash>
  2. cat hello.rb

Note: The commands given here are Unix commands and work on both Mac and Linux boxes. Unfortunately, Windows users will have to translate to their native commands.

Note: Many commands depend on the hash values in the repository. Since your hash values will vary from mine, whenever you see something like <hash> or <treehash> in the command, substitute in the proper hash value for your repository.

You should see …

Output:

  1. $ git checkout 4445720
  2. Note: checking out '4445720'.
  3. You are in 'detached HEAD' state. You can look around, make experimental
  4. changes and commit them, and you can discard any commits you make in this
  5. state without impacting any branches by performing another checkout.
  6. If you want to create a new branch to retain commits you create, you may
  7. do so (now or later) by using -b with the checkout command again. Example:
  8. git checkout -b <new-branch-name>
  9. HEAD is now at 4445720 First Commit
  10. $ cat hello.rb
  11. puts "Hello, World"

The output of the checkout command explains the situation pretty well. Older versions of git will complain about not being on a local branch. In any case, don’t worry about that for now.

Notice the contents of the hello.rb file are the original contents.

Return the latest version in the master branch

Execute:

  1. git checkout master
  2. cat hello.rb

You should see …

Output:

  1. $ git checkout master
  2. Previous HEAD position was 4445720 First Commit
  3. Switched to branch 'master'
  4. $ cat hello.rb
  5. # Default is "World"
  6. name = ARGV.first || "World"
  7. puts "Hello, #{name}!"

‘master’ is the name of the default branch. By checking out a branch by name, you go to the latest version of that branch.