git checkout

Branching and Merging

Switch branches or restore working tree files


git checkout is a versatile command that switches between branches, creates new branches, restores files from specific commits, and can put your repository in a 'detached HEAD' state. While newer Git versions split some functionality into 'git switch' and 'git restore', checkout remains widely used and understood.

Synopsis

git checkout <branch>
git checkout -b <new-branch> [<start-point>]
git checkout -B <branch> [<start-point>]
git checkout --detach [<branch>]
git checkout [--] <pathspec>...
git checkout <commit> -- <pathspec>...
[ ] optional| or<arg> placeholder... repeatable--flag option

Options

Click any option to expand

Beginner (3)

Create a new branch and switch to it immediately. Equivalent to running git branch <name> followed by git checkout <name>.

RecommendedCreates and switches in one step (modern form: git switch -c)

Example

git checkout -b feature-login

Discard unstaged changes in the specified files, restoring them from the staging area (index), not HEAD. Staged changes are kept. The -- separates file paths from branch names.

When neededDiscards unstaged edits for good — git restore <file> is the modern form

Example

git checkout -- src/app.js

Suppress feedback messages. Useful in scripts where you don't need 'Switched to branch' confirmations.

When neededSuppresses feedback; mainly for scripts

Example

git checkout -q main

Intermediate (8)

Create a new branch or reset it if it already exists, then switch to it. Useful for resetting a branch to the current commit.

Not recommendedSilently resets an existing branch and can orphan its commits

Example

git checkout -B feature-login

When creating a new branch, set up tracking configuration for the upstream branch. Allows git pull/push without specifying remote.

RecommendedCreates a local branch linked to a remote branch

Example

git checkout --track origin/feature

When creating a new branch from a remote-tracking branch, do not set up tracking. The branch will be independent.

When neededCreates a branch from a remote one without linking it as upstream

Example

git checkout --no-track -b feature origin/main

Detach HEAD at the specified commit. You can inspect old code or experiment without affecting any branch.

When neededInspect an old commit; create a branch before committing there

Example

git checkout --detach v1.0.0

Restore a file to its state at a specific commit. The file is placed in both your working directory and staging area.

When neededBrings back one file's old version, staged, without switching

Example

git checkout a1b2c3d -- src/app.js

Force checkout even with uncommitted changes. Throws away ALL local modifications to tracked files (not just conflicting ones) and any untracked files in the way.

Not recommendedThrows away all uncommitted changes to tracked files — stash instead

Example

git checkout -f main

During merge conflicts, checkout our version (the branch you were on) of the conflicted file. Useful for resolving conflicts by choosing one side. Note: during a rebase, ours/theirs are swapped.

When neededResolves a conflicted file by keeping your side (sides swap during rebase)

Example

git checkout --ours config.js

During merge conflicts, checkout their version (the branch being merged in) of the conflicted file. Accept incoming changes. Note: during a rebase, ours/theirs are swapped.

When neededResolves a conflicted file by taking the incoming side

Example

git checkout --theirs config.js

Advanced (3)

Create a new unborn branch with no commit history. The current files stay in the working tree and staging area; the first commit on this branch will have no parent, creating an independent history.

When neededStarts an unrelated history (gh-pages, docs); rarely needed

Example

git checkout --orphan gh-pages

When switching branches with local changes that touch files differing between the two branches, carry them over with a three-way merge instead of refusing; conflicts are left in the working tree to resolve. Since Git 2.55 the local changes are first saved as a stash entry, so a conflicted switch can no longer lose them.

When neededCarries local edits to another branch; may leave conflicts

Example

git checkout -m feature

Interactively select hunks to discard from the working directory. Lets you keep some changes while reverting others in the same file.

When neededDiscards selected hunks only — review each prompt carefully

Example

git checkout -p -- app.js

Choosing the Right Option

Creating Branches

Different ways to create and switch to a new branch

CommandIf Branch ExistsHistoryBest For
-b <name>Fails with errorNormal (connected)Standard new feature work
-B <name>Resets to current commitNormal (connected)Restart a branch from scratch
--orphan <name>Fails with errorNone (disconnected)gh-pages, docs, clean slate

Switching with Uncommitted Changes

What happens to your local modifications when switching branches

CommandUncommitted ChangesRisk LevelWhen to Use
git checkout <branch>Blocked if conflictSafeDefault behavior - prevents accidents
git checkout -f <branch>Discarded permanentlyDangerousAbandon all local changes intentionally
git checkout -m <branch>Merged via 3-way mergeMediumCarry changes to different branch
git stash + checkoutSaved for laterSafeTemporary context switch

Restoring Files

Discard or restore file contents from different sources

CommandSourceAffects StagingRecoverable
-- <file>Index (staged version)NoNo - changes lost forever
<commit> -- <file>Specific commitYes (staged)No - but staged for review
-p -- <file>Index (interactive)NoPartial - choose which hunks

Remote Branch Tracking

Control the relationship between local and remote branches

CommandCreates TrackingUse Casegit push/pull
--track origin/featYes (automatic)Work on teammate's branchWorks without arguments
--no-track -b exp origin/mainNo (independent)Safe experimentationRequires explicit remote
<remote-branch>Yes (if unambiguous)Quick checkout of remoteWorks without arguments

Resolving Merge Conflicts

Choose a side during merge conflicts

CommandKeepsDiscardsWhen to Use
--ours <file>Your branch's versionIncoming changesYour changes are correct
--theirs <file>Incoming versionYour changesAccept their implementation
(manual edit)Combined resultNothingNeed parts from both sides

checkout vs Modern Commands

Git 2.23+ split checkout into focused commands

CommandSwitches BranchesRestores FilesRecommended For
git checkoutYesYesFamiliarity, older Git versions
git switchYesNoClear intent: branch operations only
git restoreNoYesClear intent: file operations only

Workflow Examples

1
git stash

Save current uncommitted work

2
git checkout other-branch

Switch to the other branch

3
(review or make quick fix)

Do the necessary work on this branch

4
git checkout -

Switch back to previous branch (shortcut)

5
git stash pop

Restore your saved work

1
git checkout main

Switch to main branch

2
git pull origin main

Get latest changes from remote

3
git checkout -b feature-name

Create and switch to new feature branch

4
(make changes and commits)

Work on the feature

5
git push -u origin feature-name

Push branch and set up tracking

1
git status

See which files have been modified

2
git diff file.js

Review the changes you're about to discard

3
git checkout -- file.js

Discard changes to specific file

4
git checkout -- .

Or discard ALL unstaged changes in tracked files

1
git log --oneline

Find the commit hash you need

2
git checkout <commit-hash>

Check out that specific commit (detached HEAD)

3
(inspect, test, or debug)

Investigate the old code

4
git checkout main

Return to main branch when done

1
git log --oneline -- file.js

Find commits that changed this file

2
git show <commit>:file.js

Preview the old version

3
git checkout <commit> -- file.js

Restore file from that commit (stages it)

4
git commit -m 'Restore file.js'

Commit the restored version

1
git fetch origin

Get latest remote branch info

2
git branch -r

See available remote branches

3
git checkout --track origin/feature

Create local branch tracking the remote

4
git pull

Now pull works without specifying remote

Troubleshooting

error: Your local changes to the following files would be overwritten by checkout

Cause: You have uncommitted changes that conflict with the target branch

Either commit your changes, stash them, or use -f to force (discards changes)

git stash && git checkout branch && git stash pop

error: pathspec 'branch-name' did not match any file(s) known to git

Cause: The branch doesn't exist, or you may have typo'd the name

Check available branches with git branch -a, or create the branch with -b

git branch -a | grep branch-name

You are in 'detached HEAD' state

Cause: You checked out a commit hash or tag instead of a branch name

If you want to keep working, create a branch. Otherwise checkout an existing branch

git checkout -b new-branch-name

Commits made in detached HEAD are lost

Cause: You made commits while in detached HEAD then switched to another branch

Find the commits with reflog and create a branch to save them

git reflog && git branch recovered-work <commit-hash>

Cannot checkout: untracked file would be overwritten

Cause: You have untracked files that exist in the target branch

Either delete, move, or stash the untracked files first

git stash --include-untracked && git checkout branch

Accidentally discarded changes with checkout --

Cause: git checkout -- <file> permanently removes uncommitted changes

Unfortunately, Git cannot recover these. Check your editor's local history

(check IDE local history if available)

fatal: 'name' could be both a local file and a tracking branch

Cause: A file or folder has the same name as a remote branch you want to check out

Add a trailing -- to tell Git the name is a branch, or use git switch

git checkout branch-name --

Branch not updating after checkout

Cause: You may have checked out a remote-tracking branch directly

Create a local tracking branch instead of checking out origin/branch directly

git checkout --track origin/branch-name

Tips & Pitfalls

Best Practices

  • ✓Use 'git stash' before switching branches if you have uncommitted work you want to keep
  • ✓Prefer 'git checkout -b' over separate 'git branch' + 'git checkout' for creating and switching
  • ✓Use '--' to clearly separate file paths from branch names: 'git checkout -- file.txt'
  • ✓Consider using modern 'git switch' for branches and 'git restore' for files - clearer intent
  • ✓Use 'git checkout -' to quickly switch back to the previous branch (like 'cd -')
  • ✓Before using '-f' to force checkout, make sure you really want to discard your changes
  • ✓When in detached HEAD, create a branch immediately if you plan to make commits
  • ✓Use '--track' when checking out remote branches to set up push/pull automatically
  • ✓Use 'git checkout <commit> -- <file>' to restore specific files without switching branches
  • ✓Avoid checking out commits directly unless investigating - use branch names for regular work
  • ✓Use '-p' (patch mode) when you want to selectively discard only some changes in a file
  • ✓Always verify you're on the right branch with 'git branch' or 'git status' before starting work

Common Mistakes

  • ✗Trying to checkout with uncommitted changes. Git refuses to switch if it would overwrite your changes - either commit, stash, or use -f to force (discards changes).
  • ✗Confusing checkout for branches vs files. Accidentally restoring files when trying to switch branches - use -- before file paths: git checkout -- file.txt
  • ✗Making commits in detached HEAD state. Commits become orphaned when you checkout another branch - create a branch first: git checkout -b my-branch
  • ✗Using -B without understanding it overwrites. This can lose the existing branch's position - use -b for new branches, -B only when intentionally resetting.

FAQ

A:

'git switch' is a newer command (Git 2.23+) that only handles branch switching, making it clearer and safer. 'git checkout' can both switch branches AND restore files, which can be confusing. Use 'git switch' for branches and 'git restore' for files if you prefer the modern approach.

A:

Unfortunately, you can't undo this with Git alone - the changes are permanently discarded. Some IDEs have local history features that might help. This is why it's important to be careful with this command.

A:

Detached HEAD means you've checked out a specific commit rather than a branch. You can look around and make commits, but those commits won't belong to any branch. Create a branch with 'git checkout -b name' to save your work.

A:

'-b' creates a new branch and fails if it already exists. '-B' creates a new branch or resets an existing one to the current position. Use '-B' when you intentionally want to reset a branch.

A:

Use 'git checkout other-branch -- path/to/file'. This copies the file from that branch into your working directory and staging area. You can then commit it to your current branch.

A:

Git protects you from losing work. If switching branches would overwrite your changes, it refuses. Either commit your changes, stash them with 'git stash', or use 'git checkout -f' to force (which discards changes).

A:

It switches to the previously checked out branch, similar to 'cd -' in the shell. It's a quick way to toggle between two branches you're working on.

A:

First fetch with 'git fetch origin', then either 'git checkout branch-name' (Git auto-creates a tracking branch if origin/branch-name exists) or explicitly 'git checkout --track origin/branch-name'.

A:

Yes, use 'git checkout -p <commit> -- <file>' for interactive mode, or simply 'git checkout <commit> -- <specific-files>' to restore only certain files from that commit.

A:

Because it does two very different things: switch branches AND restore files. Git 2.23 introduced 'git switch' and 'git restore' to separate these concerns. 'git checkout' still works and is widely used.