git checkout Command
git checkout
Command
The git checkout
command is used to switch branches, restore files, or create new branches in a Git repository. It allows you to navigate between different branches or revisions, as well as manage files in your working directory.
Key Uses of git checkout
1. Switching Branches
To switch to an existing branch:
git checkout <branch-name>
<branch-name>
: The name of the branch you want to switch to.
Example:
git checkout feature/login
This command switches to the feature/login
branch, updating your working directory to match the state of that branch.
2. Creating and Switching to a New Branch
To create a new branch and switch to it in one command:
git checkout -b <branch-name>
-b
: Creates a new branch and checks it out.
Example:
git checkout -b feature/login
This command creates the feature/login
branch and switches to it.
3. Restoring Files
To restore a file from the index (staging area) to match the last commit:
git checkout -- <file>
<file>
: The path to the file you want to restore.
Example:
git checkout -- file.txt
This restores file.txt
to its state in the last commit, discarding any changes made since then.
To restore a file from a specific commit:
git checkout <commit> -- <file>
<commit>
: The commit hash or reference from which to restore the file.
Example:
git checkout abc1234 -- file.txt
This restores file.txt
to its state in commit abc1234
.
Important Notes
Unstaged Changes: When switching branches, if you have uncommitted changes in your working directory, Git may prevent the switch if it would cause conflicts. You can either commit, stash, or discard changes before switching.
Deprecated for Some Uses: The
git checkout
command has been partially deprecated in favor ofgit switch
andgit restore
for switching branches and restoring files, respectively.
Summary
- Purpose:
git checkout
is used to switch branches, create new branches, and restore files in a Git repository. - Basic Commands:
git checkout <branch-name>
: Switch to an existing branch.git checkout -b <branch-name>
: Create and switch to a new branch.git checkout -- <file>
: Restore a file from the index to match the last commit.git checkout <commit> -- <file>
: Restore a file from a specific commit.
The git checkout
command is a versatile tool for managing branches and file states within your Git repository, though for some operations, it has been supplemented by git switch
and git restore
for clarity and simplicity.