git checkout
Using git checkout along with a branch name or commit hash lets you switch between branches or inspect your repository at a previous point in time.
Changing branches
To switch to a different branch:
$ git checkout my-other-branch
Switched to branch 'my-other-branch'
This changes your working copy to the latest commit (HEAD) of that branch. To create a new branch and switch to it in one step:
$ git checkout -b my-new-branch
Switched to a new branch 'my-new-branch'
The new branch starts from wherever you currently are, including any uncommitted or unstaged changes. For more on managing branches, see git branch.
Checking out a specific commit
You can also check out a specific commit by its hash:
$ git checkout 956951bfc15e077bf6dac35ee552117f5a7e8a43
Note: checking out '956951bfc15e077bf6dac35ee552117f5a7e8a43'.
You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.
HEAD is now at 956951b Revert "Remove Cheddar"
In this "detached HEAD" state, you're viewing a snapshot of the repository at that commit. You can browse and experiment freely without affecting any branch. If you decide to keep your changes, create a new branch from here with git checkout -b my-fix. For a deeper explanation, see What is Git detached HEAD?
Discarding changes to a file
If you've modified a file and want to discard those changes, restoring it to the version in your last commit:
$ git checkout -- src/config.js
The -- tells Git you're referring to a file path, not a branch. This is useful when you've been experimenting and want to throw away uncommitted edits to specific files without affecting the rest of your working directory.
Modern alternatives: git switch and git restore
Since Git 2.23, the checkout command has been split into two more focused commands:
git switchhandles branch switching:git switch my-branchorgit switch -c new-branchgit restorehandles file restoration:git restore src/config.js
These commands do the same things as git checkout, but with clearer intent. The original git checkout still works and isn't going away — you'll see it in most existing tutorials and documentation. Use whichever you prefer.
Using checkout with merges and deployments
Switching branches is a core part of the branching and merging workflow. You'll typically check out your main branch before merging in feature work, and check out feature branches to continue development.
Once your code is ready, DeployHQ can automatically deploy changes from any branch to your server — so you can map branches to environments (e.g. staging deploys to your staging server, main deploys to production) without any manual steps.