How to Checkout/Clone From a Specific Git Commit Id (SHA)

Checkout From a Specific Git Commit Id

There are scenarios where you might need to checkout or clone from a specific git commit id. For example, you might want to perform a git pull on a specific commit version for troubleshooting.

This blog explains the steps involved in checking out a specific git commit ID (SHA).

Important Note: Always keep a backup of your code with all the commit histories before performing any git activity that may change or reverse the code.

Checkout From Specific Git Commit ID

Follow the steps to checkout from a specific commit id.

Step 1: Clone the repository or fetch all the latest changes and commits.

Step 2: Get the commit ID (SHA) that you want to checkout. From your local repository, you can get the commit SHA from the log. If you are using any platforms like Github, you can get the SHA id from the GUI itself.

git log

Step 3: Copy the commit (SHA) id and checkout using the following command.

git checkout 28cd74decb47d8a5294eb59e793cb24a0f242e9e

You can also use the short form of the SHA ID from the start, as shown below.

git checkout 28cd74de

You need to be very careful with this checkout. It will be in the detached HEAD mode. Meaning, you can play around with making the changes without impacting any branches. So if you need to make any actual changes to a specific commit, use a branch checkout as explained in the next step.

Step 4: If you want to make changes from the commit ID checkout, you need to create a branch, as shown below.

git checkout -b <new-branch-name> <commit-id-sha>

For example,

git checkout -b test-branch 7d4c59f5

This will retain everything from the commit ID to the test-branch.

Git Clone From Specific Commit ID

There is no direct way to clone directly using the commit ID. But you can clone from a git tag.

However, you can do the following workaround to perform a clone if it is really necessary.

  1. Clone the repository
  2. Perform a hard reset with commit SHA id

The above steps will make your current HEAD pointing to the specific commit id SHA.

For example,

git clone <repository>
git reset --hard <COMMIT-SHA-ID>

Set Git HEAD to Specific Commit ID

If you want to revert your HEAD to a specific commit, perform a hard reset with the latest commit SHA after pulling the changes, as shown below.

git pull
git reset --hard 7d4c59f5

To revert it back, you can perform a git pull that will get all the changes from the upstream branch.

Also, learn how to checkout a git pull request.

Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like