Git

How to Checkout a Specific Commit in Git?

Git is probably the most popular and most respected version control system. Large companies and individual developers use it to track and share their code and projects. It allows developers to collaborate from every point of the world and revert changes to codes if need.

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.

Credit: https://github.com/leachim6

Start by cloning the repository:

$ git clone https://github.com/leachim6/hello-world

After cloning the repository, navigate to the repository:

$ cd hello-world

To view all the commits in the master branch, use the command:

$ git log

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:

$ git checkout 8e2e9aa71ca94b74a9d9048841d95d408ff7db3b

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:

$ git switch –

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.

Conclusion

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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list