How to Use Git Checkout to Switch Branches and Revisit Commits

The git checkout command is a versatile tool used primarily to switch between different versions of a project, whether it is a branch or a specific commit.

Follow the guide:

  1. Switching to a Branch:
    1. To view existing branches:
      git branch
    2. To switch to a branch:
      git checkout <branch-name>
  2. Creating a New Branch:
    1. To create and switch to a new branch:
      git checkout -b <new-branch-name>

      This is ideal for working on new features or fixes without affecting the main codebase.

  3. Checking Out a Commit (Detached HEAD):
    1. You can also use git checkout to switch to a specific commit:
      git checkout <commit-hash>

      Note: You only need the first 5–7 characters of the commit hash.

    2. This puts you in a “detached HEAD” state—meaning you’re viewing a past snapshot of the project, not on any branch. Changes made here won’t affect your branches unless you create a new branch from this state:
      git switch -c <new-branch-name>
    3. To return to your previous branch:
      git switch –
  4. Using Checkout to Deploy Files:
    The checkout command can also help deploy files using a script. Example:

    #!/bin/sh
    git --work-tree=/home/userna5/public_html --git-dir=/home/userna5/production.git checkout -f
    • –work-tree: Target directory for deployment
    • –git-dir: Location of the repository

This pushes your current project files to a specific location, ideal for local or remote deployment.

Hope you liked our article. If you require additional assistance, feel free to contact our support staff.

For step-by-step instructions, read our article on how to install Git on Windows 10.

Popular Posts You May Read

Explore more hosting insights, tips and industry updates.

How to Allot WHM Feature List to cPanel

In this article, you will explore the process of allot WHM feature list to cPanel.…

Explore the Debian Packages with Apt-file

Apt-file to explore the Debian packages: when one uses only the command line on Linux,…

What is 204 Status Code? A Beginner-Friendly Guide

What is 204 Status Code? A Beginner-Friendly Guide

HTTP status codes help you understand how a server responds to a request made by…