Git Checkout
The git checkout command switches, creates and restores branches in the working directory to a specific state. The git checkout command also allows switching to a specific commit without changing branches.
Syntax
Checkout with branches:
git checkout [options] <branch-name>
<branch-name>specifies the name of the branch to switch to or create.[options]optional flags that can be used with the checkout command. Here are some of the most commonly used options:-bcreates a new branch with the specified name and switches to it immediately.-returns to the previously checked-out branch. This flag does not need the<branch-name>.-f(–force) forces the checkout, discarding any local changes in the working directory.
Checkout to a specific commit:
git checkout <commit-hash>
Switch to an existing branch
The following command will switch to an already existing branch, created previously with the git branch command:
git checkout existing-branch
Note: From Git 2.23, the new specific
git switchcommand has been introduced to switch branches, making it clearer and safer thangit checkoutbecause it avoids the ambiguity of the latter’s multi-purpose nature.
Create and switch to a new branch
It is possible to create and switch to a new branch with a single command using the -b option:
git checkout -b new-branch
Restore a file from a specific commit
git checkout also allows to restore a file from a specific commit using its hash:
git checkout <commit-hash> -- example.txt
Examine a Previous Commit
git checkout also allows temporarily moving to a specific commit without changing branches. This state is called detached HEAD state:
git checkout <commit-hash>
The detached HEAD state allows to:
- Examine the state of the repository at that specified commit.
- Create new branches if the developer needs to start from that point.
- Any code changes made in this state will not be associated with any existing branch unless a new branch is created.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Git on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Use our beginner friendly Git course to integrate Git and GitHub and manage versions of your projects using Git branches.
- With Certificate
- Beginner Friendly.4 hours