Git and GitHub – Git Checkout (Part-6)

Posted by

1. Switching Branches

Scenario: You have multiple branches in your repository, and you want to switch from the current branch to another branch.


  1. List Branches:
git branch

* master

Switch to feature-branch:

git checkout feature-branch

Switched to branch 'feature-branch'
  • Explanation: This command switches the working directory to the feature-branch.

2. Creating and Switching to a New Branch

Scenario: You want to create a new branch called new-feature and switch to it.


  1. Create and Switch to a New Branch:
git checkout -b new-feature

Switched to a new branch 'new-feature'
  • Explanation: The -b flag creates a new branch called new-feature and switches to it.

List Branches to Verify:

git branch

* new-feature
  • Explanation: The new-feature branch is now the current branch (indicated by *).

3. Checking Out a Specific Commit

Scenario: You want to view the state of the repository at a specific commit.


  1. Get the Commit Hash:
git log

commit 7062f9ba83b7f96f3b722be237935c0c30ac5de4 (HEAD -> master)
Author: Jami Raj <>
Date:   Tue May 28 16:07:13 2024 -0700


commit 3d0f84561e39cdfc6724c77b2b135e245dc6bf22
Author: Jami Raj <>
Date:   Tue May 28 16:05:15 2024 -0700

  • Explanation: Note the commit hash you want to check out (e.g., 3d0f84561e39cdfc6724c77b2b135e245dc6bf22).
git checkout 3d0f84561e39cdfc6724c77b2b135e245dc6bf22

Note: switching to '3d0f84561e39cdfc6724c77b2b135e245dc6bf22'.

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>

Or undo this operation with:

  git switch -

Turn off this advice by setting config variable advice.detachedHead to false

HEAD is now at 3d0f845 file1

Explanation: This switches the working directory to the state at the specified commit. You are in a “detached HEAD” state, meaning you are not on any branch.

Restoring a File to a Previous State

Scenario: You want to restore a specific file to its state at a previous commit.


  1. Check Out the File from a Specific Commit:
git checkout 3d0f84561e39cdfc6724c77b2b135e245dc6bf22 --

Updated 1 path from 3d0f845

Explanation: This restores to its state at the specified commit without switching the entire working directory to that commit.

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x