Checking Out a Specific Commit with Git Checkout
Another functionality retained by git checkout is the ability to check out a specific commit. This puts you in a "detached HEAD" state, allowing you to inspect the project at that point in history. git switch does not have this capability.
First, let's find the commit hash of the initial commit.
Ensure you are in the project directory:
cd ~/project
View the commit history:
git log --oneline
You will see output similar to this, with the commit hashes:
<commit_hash_development> (HEAD -> development) Initial commit
<commit_hash_main> (main, feature-branch) Initial commit
Note that the commit hashes will be different in your environment. Copy the commit hash for the "Initial commit".
Now, use git checkout followed by the commit hash to check out that specific commit. Replace <commit_hash> with the actual hash you copied.
git checkout <commit_hash>
You will see output indicating that you are in a detached HEAD state:
Note: switching to '<commit_hash>'
You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by switching back to a branch.
If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -c with the switch command. Example:
git switch -c <new-branch-name>
HEAD is now at <commit_hash> Initial commit
You are now viewing the project as it was at the time of the initial commit. To return to a branch, you can use git switch or git checkout to switch back to a branch like development or main.
Let's switch back to the development branch using git switch:
git switch development
You will see output confirming the switch:
Switched to branch 'development'
You have successfully used git checkout to explore a specific commit and then returned to a branch using git switch.