git checkout
git checkout
: check out a branch or restore working tree files.
The git checkout
command is a versatile command in Git that allows you to navigate between branches, restore files, and switch to specific commits. However, in recent versions of Git, many of its functionalities have been split into two new commands: git switch
and git restore
, to provide a clearer and more focused set of commands.
The primary purpose of git checkout
is to switch between different branches or restore files to a previous state. It helps developers work on multiple features or bug fixes simultaneously by allowing them to switch between different branches easily. It also enables them to revert changes made to files, providing a safety net in case of mistakes or experimentation.
Check out
this peculiar thread on StackOverflow to find out.
Examples
Switch to an existing branch:
git checkout feature-branch
Create a new branch and switch to it right away:
git checkout -b new-feature
Restore a file to the state of the last commit. Note that the special --
option is used to tell Git that all the following arguments are file paths. This is necessary to avoid ambiguity when a file path may be mistaken for a branch or commit:
git checkout -- path/to/file.js
Switch to a specific commit (detached HEAD state, meaning you're not on a branch):
git checkout 1a2b3c4d
However, in newer versions of Git (2.23+), it's recommended to use git switch
for branch switching and git restore
for file restoration. This separation of concerns makes the commands more intuitive and less error-prone.
Switch to an existing branch (Git 2.23+):
git switch feature-branch
Create a new branch and switch to it (Git 2.23+):
git switch -c new-feature
Restore a file to the state of the last commit (Git 2.23+):
git restore path/to/file.js
In summary, while git checkout
is still widely used and supported, it's a good practice to start using git switch
and git restore
for clearer and more specific actions in your Git workflow. This helps to avoid confusion and potential mistakes, especially for newcomers to Git.
Hi! I'm Alex, creator of GitByBit.
And this is Gitopedia—a reference that summarizes knowledge in my Git course.
Gitopedia is designed to be a personal knowledge base. When you progress through the main Git course in VS Code, you unlock all of these topics, one by one, bit by bit. This gives you time to digest the information and gradually build the mental model of Git. Here's an example of how it works:
Learning directly in VS Code lets you practice Git exactly as you would in real life, doing real jobs, writing real code. In addition, the course has access to your actual terminal, so it can point out mistakes, suggest workarounds, etc.
The course is FREE, there are no Ads or other bullshit. There are optional premium add-ons you can purchase, mainly to support my work (regrettably, I have to eat every day), but that's totally up to you.