git checkout
Description:
Switch between branches or restore files from commits. This is Git's Swiss Army knife command with multiple uses.
Syntax:
bash
git checkout <branch-name>
git checkout -b <new-branch>
git checkout <commit-hash>
git checkout -- <file>Examples:
bash
# Switch to existing branch
git checkout develop
# Create and switch to new branch in one command
git checkout -b feature/shopping-cart
# Switch to a specific commit (detached HEAD state)
git checkout abc1234
# Create branch from specific commit
git checkout -b bugfix/issue-42 abc1234
# Discard changes to a file (restore from last commit)
git checkout -- index.html
# Restore all files in directory
git checkout -- .
# Switch to previous branch
git checkout -
# Checkout specific file from another branch
git checkout main -- config.jsonDetailed Explanation:
- Multi-purpose command: Can switch branches, restore files, or view old commits
- Updates working directory: Changes files in your working directory to match the target branch/commit
- Detached HEAD: Checking out a commit (not a branch) puts you in "detached HEAD" state
- Being replaced: Newer Git versions introduce
git switchandgit restoreto separate these functions
Common Errors:
error: pathspec 'branch' did not match any file(s)→ Solution: Branch doesn't exist; usegit branchto verify or create iterror: Your local changes would be overwritten→ Solution: Commit, stash, or discard your changes firstYou are in 'detached HEAD' state→ Solution: This is a warning; create a branch if you want to keep work:git checkout -b new-branchfatal: reference is not a tree→ Solution: Invalid commit hash; check withgit log
Pro Tips:
- Use
git switchinstead ofgit checkoutfor switching branches (clearer intent) - Use
git restoreinstead ofgit checkout --for restoring files (more explicit) - Save time:
git checkout -switches to the previous branch (likecd -) - Checkout remote branch:
git checkout -b local-name origin/remote-branch - Warning:
git checkout -- filediscards all changes permanently; use with caution.
Related Commands:
git switch– Modern alternative for switching branchesgit restore– Modern alternative for restoring filesgit branch– List or create branchesgit stash– Temporarily save changes before switching