Appearance
Git Switch & Restore Quick Reference
Branch Operations (use git switch)
| Goal | Command |
|---|---|
| Switch to existing branch | git switch main |
| Create and switch | git switch -c feature/new |
| Switch to previous branch | git switch - |
| Detach at a tag/commit | git switch --detach v2.4.0 |
| Switch with auto-stash | git switch --merge feature/x |
| Force switch (discard changes) | git switch --discard-changes main |
File Operations (use git restore)
| Goal | Command |
|---|---|
| Discard uncommitted changes | git restore main.go |
| Discard all changes | git restore . |
| Restore from another commit | git restore --source a1b2c3d main.go |
| Restore from another branch | git restore --source feature/x deploy/helm/values.yaml |
| Unstage a file | git restore --staged main.go |
| Unstage and restore working tree | git restore --staged --worktree main.go |
| Interactive hunk restoration | git restore --patch main.go |
| Restore with pathspec exclude | git restore -- ':!:*_test.go' 'src/' |
CI/CD One-Liners
bash
# CI-safe branch switch
git switch --discard-changes release/2.4 && make build && git switch --discard-changes main
# Restore config from release tag without touching working tree
git restore --source v2.4.0 -- config/production.yaml
# Unstage generated artifacts but keep files for debug
git restore --staged -- 'dist/*.js'
# Unstage everything
git restore --staged .
# Restore accidentally deleted file from main
git restore --source main -- deploy/helm/values.yamlOld-to-New Mapping
Old git checkout | New Command |
|---|---|
checkout <branch> | switch <branch> |
checkout -b <branch> | switch -c <branch> |
checkout <tag> | switch --detach <tag> |
checkout -- <file> | restore <file> |
checkout <commit> -- <file> | restore --source <commit> <file> |
reset HEAD <file> | restore --staged <file> |
checkout -p | restore --patch |
Version Check
bash
if [ "$(git --version | cut -d' ' -f3 | cut -d. -f1)" -lt 2 ] || \
[ "$(git --version | cut -d' ' -f3 | cut -d. -f2)" -lt 23 ]; then
echo "fallback: git checkout"; else echo "git switch/restore available"
fiShell Aliases
bash
alias gco='git switch'
alias grs='git restore'
alias gcb='git switch -c'