This tutorial will look at reverting to a specific commit in a specific repository using the git checkout command.
What is a Commit?
In Git, a commit refers to a snapshot of a file or a collection of files in a repository. Think of it as the instances you press save in a document. However, unlike save, Git creates a specific identifier, allowing you to view or event revert to that specific save.
What is Git Checkout?
On the other hand, Git checkout means using a specific commit as your most recent commit. In most cases, you will want to checkout specific branches and not commits. However, if the need arises, Git does support checking out commits.
How to Checkout a Specific Commit
Let us now drill down to the bedrock of the tutorial. To checkout a specific commit, ensure you have the repository cloned to your local machine.
To illustrate example, let’s use a repository that contains “Hello world” in all languages.
Start by cloning the repository:
After cloning the repository, navigate to the repository:
To view all the commits in the master branch, use the command:
This will show all the git commit history as shown in the example below:
To checkout the specific commit, we need the SHA1 identifier as shown in the git log command.
For example, suppose we need to checkout the commit “8e2e9aa71ca94b74a9d9048841d95d408ff7db3b”, we can use the command:
The output is as shown:
Once you have the checkout complete, you can perform all the changes in the repository and save it.
To revert to the current head, use:
NOTE: Checking out a specific commit creates a detached head. A detached head means that after checking out a commit, all the changes made from that point do not belong to any branch unless a new one is created containing changes from that commit.
In this quick guide, we talked about how to checkout a specific commit in a repository. Although this is not very common, it can be helpful to do so.