The git checkout command is one of the most useful and flexible tools in Git. It allows you to switch between branches, revisit older commits, and even deploy files. Whether you’re working on new features or reviewing past changes, mastering this command can make version control much easier.
In this guide, we’ll explain how to use git checkout effectively — from switching branches to deploying code safely.
Before switching branches, you can view all existing branches in your repository using:
git branch
To switch to a specific branch, use:
git checkout <branch-name>
Tip: The active branch will be marked with an asterisk (*) in the list.
This command allows you to move from one branch to another — for example, switching from the main branch to development.
If you need to create a new branch and switch to it immediately, use:
git checkout -b <new-branch-name>
This is ideal when working on a new feature, bug fix, or experimental code, as it keeps your main branch clean and stable.
Git also lets you revisit a specific commit in your project’s history.
Use the commit hash (first 5–7 characters are enough):
git checkout <commit-hash>
This action puts you in a detached HEAD state, meaning:
To save your changes from this state, create a new branch:
git switch -c <new-branch-name>
To return to your previous branch:
git switch –
The git checkout command can also be used for deployment purposes, especially when automating code delivery to a server or public directory.
Here’s an example deployment script:
#!/bin/sh
git –work-tree=/home/userna5/public_html –git-dir=/home/userna5/production.git checkout -f
Explanation:
This method is useful for local or remote deployments, allowing developers to push updated code directly to a web directory.
| Task | Command | Description |
| View existing branches | git branch | Lists all branches in the repository |
| Switch to another branch | git checkout <branch-name> | Moves to an existing branch |
| Create and switch to a new branch | git checkout -b <new-branch-name> | Creates and moves to a new branch |
| Checkout a specific commit | git checkout <commit-hash> | Views a past version of the project |
| Create new branch from commit | git switch -c <new-branch-name> | Saves changes made in detached HEAD |
| Return to previous branch | git switch – | Goes back to last branch |
| Deploy files via checkout | git –work-tree=<path> –git-dir=<repo> checkout -f | Deploys code to target directory |
Using git checkout effectively helps developers:
If you manage development projects and host applications online, you need a reliable hosting environment that supports version control and deployment workflows.
At host.co.in, we provide:
Explore Linux VPS Hosting Plans