Skip to content

Git Switch & Restore Quick Reference ​

Branch Operations (use git switch) ​

GoalCommand
Switch to existing branchgit switch main
Create and switchgit switch -c feature/new
Switch to previous branchgit switch -
Detach at a tag/commitgit switch --detach v2.4.0
Switch with auto-stashgit switch --merge feature/x
Force switch (discard changes)git switch --discard-changes main

File Operations (use git restore) ​

GoalCommand
Discard uncommitted changesgit restore main.go
Discard all changesgit restore .
Restore from another commitgit restore --source a1b2c3d main.go
Restore from another branchgit restore --source feature/x deploy/helm/values.yaml
Unstage a filegit restore --staged main.go
Unstage and restore working treegit restore --staged --worktree main.go
Interactive hunk restorationgit restore --patch main.go
Restore with pathspec excludegit 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.yaml

Old-to-New Mapping ​

Old git checkoutNew 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 -prestore --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"
fi

Shell Aliases ​

bash
alias gco='git switch'
alias grs='git restore'
alias gcb='git switch -c'

Git Master — Git Reference for Every Skill Level