How to Checkout a Commit in Git
In Git, checking out a specific commit allows you to view or work with your repository at a particular point in its history. Here’s a straightforward guide to help you do it.
1. Find the Commit Hash
Each commit in Git has a unique identifier called a hash. To find the hash of the commit you want to check out, use:
This shows the commit history. Look for the hash (e.g., abc123
) of the desired commit.
2. Checkout the Commit
To check out a specific commit, run:
For example:
Detached HEAD State
When you checkout a commit directly, Git puts you in a detached HEAD state. This means you’re no longer on a branch, and any changes you make will not be associated with a branch unless you create one.
3. Create a New Branch (Optional)
If you want to make changes starting from this commit, create a new branch:
For example:
This creates a new branch from the checked-out commit and switches to it.
4. Return to a Branch
To leave the detached HEAD state and return to a branch, use:
For example:
Summary
Use
git log
to find the commit hash.Run
git checkout <commit-hash>
to view the commit.To make changes, create a new branch with
git checkout -b <branch-name>
.To return to a branch, use
git checkout <branch-name>
.
Checking out commits is a powerful way to explore your repository's history or start new work from a specific point.