https://tduyng.com/atom.xml

Git Checkout vs. Git Switch

git checkout

  • Switch branches:

    git checkout <branch>        # Switch to an existing branch
    
  • Create and switch to a new branch:

    git checkout -b <new-branch> # Create and switch to a new branch
    
  • Restore files from a specific commit or branch:

    git checkout <commit> -- <file> # Restore a file from a specific commit
    

git switch (modern alternative)

  • Switch branches:

    git switch <branch>          # Switch to an existing branch
    
  • Create and switch to a new branch:

    git switch -c <new-branch>   # Create and switch to a new branch
    

Key differences

CommandPurposeNotes
git checkout <branch>Switch branchesOlder, more versatile command.
git checkout -b <branch>Create and switch to a new branchCombines branch creation and switch.
git checkout <commit> -- <file>Restore a file from a commitUseful for recovering files.
git switch <branch>Switch branchesModern, focused alternative.
git switch -c <branch>Create and switch to a new branchSimpler and more intuitive.

When to use?

  • git checkout:

    • Use for restoring files from a specific commit or branch.
    • Still works for switching branches, but git switch is preferred.
  • git switch:

    • Use for switching branches or creating new branches.
    • Cleaner and more focused than git checkout.

Pro tips

  • Recover deleted branches:

Use git reflog to find the branch’s last commit, then recreate it:

git switch -c <branch> <hash>
  • Use git switch for branch operations. It’s designed specifically for branches, making it more intuitive.

2025/01/15 08:00 PM