Introduction

Sometimes one may want to checkout a past revision, or in simpler terms a change that was made in the past in a certain commit to experiment with the change. Checking out the commit (not the branch) might be it.

Let’s dive right in!

How to checkout a commit to use a passed revision/change

It’s good to think of a branch as a “snapshot” of the current main/master(depends on what you name your master branch) with parallel changes that would later be merged into master/main branch. Branches point to these changes with the latest commits for any activity on the branch.

A commit is identified by a commit hash that references the changes made in that commit activity.

1. Checking out a branch

Checking out a branch makes git super useful. Say you are working on a new feature, let’s call it “adding dark theme”. A usual action would be:

  1. sync your master/main, by doing git pull to pull in and sync the current changes(assuming the repository has a remove hosted on Github or any other platform)
  2. Checkout(create) your feature branch, by running git checkout -b feat-add-dark-theme
  3. Once switched to the new branch, begin hacking while committing changes on this feat-add-dark-theme,
  4. Once done, push changes to the remote and create a Pull Request

A pull request, is analogous to, “here are some changes I made working on issue-x, mind having a look?”, then afterward, the repo owner and the maintainers would do the needful to incorporate the changes or request changes and provide meaningful changes.

2. Checking out a commit

Checking out a commit has no real benefit except using certain changes down the commit history based on a commit hash, each commit has a unique commit has that points to changes made at that commit activity along the commit activities made in the past on that branch.

Things to note:

  • checking out a commit leave your repository in Detached HEAD state, all changes made are not linked to any branch and can be lost
  • Changes do not belong to any branch, checking out to a different branch discards all the changes made while at that checked out commit/revision

To checkout a commit/passed revision:

git checkout <commit-hash>

Each commit has an associated commit hash that’s unique to that commit, if using git with Github, such commit can be seen with the commit message for a given commit:

a code snippet screenshot

Checking out the past revision would be:

git checkout 28f7efe54d287ea888a3a157aa87529f2c8651ba

The result of this would be a “detached” temporary, won’t call it a branch, git switches to changes at that commit hash.

Summary

Checking out a commit/ past revision can be a great way to experiment with a past revision/commit.

However, checking out a commit does not provide any other benefit. It’s good also to have a backup of the repository and be sure that checking out a commit/revision is what one wants to achieve.