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.

Changing The Templates in Joomla 1.5

This tutorial is designed to help you change the template in Joomla 1.5, you will…

How Much Bandwidth Do I Require on My Web Server?

When choosing any web hosting package, you will find that one of the major factors…

How to Check and Repair a Database in phpMyAdmin

This article helps you in understanding how to check and repair a database using phpMyAdmin…