Skip to content
Unverified — AI-generated content. Help verify this page

Git Cheat Sheet

Quick reference for Git commands, branching strategies, undo operations, and rebase workflows.


Setup & Config

CommandDescription
git config --global user.name "Name"Set your name
git config --global user.email "email"Set your email
git config --global core.editor "code --wait"Set editor to VS Code
git config --global init.defaultBranch mainDefault branch name
git config --global pull.rebase trueRebase on pull by default
git config --global fetch.prune trueAuto-prune on fetch
git config --global diff.algorithm histogramBetter diff algorithm
git config --list --show-originShow all config with source

Daily Workflow

Basic Commands

CommandDescription
git statusShow working tree status
git add fileStage specific file
git add -pStage hunks interactively
git add .Stage all changes in current dir
git commit -m "msg"Commit with message
git commit -am "msg"Stage tracked files and commit
git commit --amendAmend last commit
git commit --amend --no-editAmend without changing message
git pushPush to remote
git push -u origin branchPush and set upstream
git pullFetch and merge (or rebase)
git fetchFetch without merging
git fetch --all --pruneFetch all remotes, prune deleted

Branching

CommandDescription
git branchList local branches
git branch -aList all branches (local + remote)
git branch featureCreate branch
git checkout featureSwitch to branch
git checkout -b featureCreate and switch
git switch featureSwitch to branch (modern)
git switch -c featureCreate and switch (modern)
git branch -d featureDelete merged branch
git branch -D featureForce delete branch
git push origin --delete featureDelete remote branch
git branch -m old newRename branch

Merge & Rebase

CommandDescription
git merge featureMerge feature into current
git merge --no-ff featureMerge with merge commit
git merge --squash featureSquash all commits, do not commit
git rebase mainRebase current onto main
git rebase --onto main A BRebase B onto main from A
git rebase --continueContinue after resolving conflicts
git rebase --abortAbort rebase
git cherry-pick abc123Apply specific commit
git cherry-pick A..BApply range of commits

Viewing History

CommandDescription
git log --onelineCompact log
git log --oneline --graphLog with branch graph
git log --oneline -20Last 20 commits
git log --author="Name"Commits by author
git log --since="2 weeks ago"Commits in timeframe
git log --follow fileFile history across renames
git log -p fileFile history with diffs
git log main..featureCommits in feature not in main
git diffUnstaged changes
git diff --stagedStaged changes
git diff main..featureDiff between branches
git diff --statSummary of changes
git blame fileLine-by-line attribution
git show abc123Show commit details
git shortlog -snCommit count by author

Undo Operations

This is the most critical section. Choose carefully.

Undo Staged Changes

bash
# Unstage a file (keep changes in working tree)
git restore --staged file

# Unstage all files
git restore --staged .

# Legacy syntax
git reset HEAD file

Undo Working Tree Changes

bash
# Discard changes to a file
git restore file

# Discard all working tree changes
git restore .

# Legacy syntax
git checkout -- file

Undo Commits

ScenarioCommandEffect
Undo last commit, keep changes stagedgit reset --soft HEAD~1Commit removed, changes staged
Undo last commit, keep changes unstagedgit reset HEAD~1Commit removed, changes in working tree
Undo last commit, discard changesgit reset --hard HEAD~1Commit and changes gone
Undo a pushed commit (safe)git revert abc123New commit that undoes the changes
Undo multiple pushed commitsgit revert A..BRevert range

Recovery

bash
# Find lost commits (reset, rebase, etc.)
git reflog

# Restore to a reflog entry
git reset --hard HEAD@{3}

# Recover a deleted branch
git reflog
git checkout -b recovered abc123

WARNING

git reset --hard permanently discards uncommitted changes. There is no undo. Always git stash first if unsure.


Stash

CommandDescription
git stashStash working changes
git stash -uStash including untracked files
git stash push -m "msg"Stash with description
git stash listList all stashes
git stash popApply and remove latest stash
git stash applyApply without removing
git stash apply stash@{2}Apply specific stash
git stash drop stash@{0}Delete specific stash
git stash clearDelete all stashes
git stash show -pShow stash diff

Branching Strategies

GitHub Flow (Simple)

Best for: Teams shipping frequently, single production branch.

main ─────●─────●─────●─────●─────
           \         /
  feature   ●───●───●

Rules:

  1. main is always deployable
  2. Branch from main for features
  3. Open a Pull Request
  4. Merge to main after review
  5. Deploy main

Git Flow (Complex)

Best for: Versioned releases, multiple environments.

main    ─────●───────────────●─────
              \             /
release        ●───●───●───●
              /         \
develop ─●───●───●───●───●───●─────
          \     /
  feature  ●───●

Branches: main, develop, feature/*, release/*, hotfix/*

Trunk-Based Development

Best for: CI/CD-mature teams, continuous deployment.

main ─●─●─●─●─●─●─●─●─●─●─●─●─
       \/ \/ \/
  short-lived branches (< 1 day)

Rules:

  1. main is the trunk
  2. Feature branches live less than 1 day
  3. Feature flags for incomplete work
  4. All commits pass CI before merge

When to Use Which

StrategyTeam SizeRelease CadenceComplexity
GitHub Flow1-10ContinuousLow
Trunk-Based5-100+ContinuousLow
Git Flow5-50Scheduled releasesHigh

Rebase Workflows

Interactive Rebase

bash
# Rebase last 5 commits
git rebase -i HEAD~5

Commands in the editor:

CommandEffect
pickKeep commit as is
rewordKeep commit, change message
editPause to amend commit
squashMerge into previous, keep message
fixupMerge into previous, discard message
dropRemove commit
reorderMove lines to reorder commits

Common Rebase Patterns

bash
# Clean up feature branch before merging
git rebase -i main

# Squash fixup commits
# Mark fixup commits as "fixup" in the editor

# Move a branch to the latest main
git checkout feature
git rebase main

# If conflicts occur during rebase
git status                  # See conflicted files
# Fix the conflicts
git add .
git rebase --continue

Rebase vs Merge

AspectRebaseMerge
HistoryLinear, cleanPreserves branch history
ConflictsResolved per-commitResolved once
SafetyRewrites historyNon-destructive
Shared branchesNEVER rebase shared branchesAlways safe
WhenBefore merging feature to mainWhen merging to main

Golden Rule

Never rebase commits that have been pushed to a shared branch. Rebase is for cleaning up local commits before pushing or merging.


Tags

CommandDescription
git tag v1.0.0Lightweight tag
git tag -a v1.0.0 -m "Release 1.0.0"Annotated tag
git tag -a v1.0.0 abc123Tag a specific commit
git push origin v1.0.0Push specific tag
git push origin --tagsPush all tags
git tag -d v1.0.0Delete local tag
git push origin --delete v1.0.0Delete remote tag
git tag -l "v1.*"List tags matching pattern

Worktrees

CommandDescription
git worktree add ../hotfix hotfix-branchCreate worktree for branch
git worktree listList worktrees
git worktree remove ../hotfixRemove worktree

Use worktrees to work on multiple branches simultaneously without stashing.


Troubleshooting

Common Problems

ProblemSolution
Committed to wrong branchgit reset --soft HEAD~1, switch branch, commit
Need to split a commitgit reset HEAD~1, stage and commit in parts
Merge conflict on binary filegit checkout --theirs file or --ours
Accidentally deleted a branchgit reflog, find the commit, recreate branch
Push rejected (non-fast-forward)git pull --rebase then push
Large file accidentally committedgit filter-branch or git-filter-repo
Need to find which commit introduced a buggit bisect start, git bisect bad, git bisect good v1.0

.gitignore Not Working

bash
# If files are already tracked, .gitignore won't help
# Remove from tracking (keep file on disk)
git rm --cached file

# Remove directory from tracking
git rm -r --cached dir/

# Regenerate index
git rm -r --cached .
git add .
git commit -m "fix: apply .gitignore"

Useful Aliases

bash
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status
git config --global alias.last 'log -1 HEAD'
git config --global alias.lg 'log --oneline --graph --all --decorate'
git config --global alias.undo 'reset --soft HEAD~1'
git config --global alias.wip 'commit -am "WIP"'

Test Yourself
  1. What command stages changes interactively by hunk?git add -p

  2. How do you create and switch to a new branch in one command (modern syntax)?git switch -c feature

  3. What command undoes the last commit but keeps changes staged?git reset --soft HEAD~1

  4. How do you stash changes including untracked files?git stash -u

  5. What command shows commits in branch B that are not in branch A?git log A..B

  6. How do you force-delete a branch that has not been merged?git branch -D feature

  7. What interactive rebase command merges a commit into the previous one while discarding its message?fixup

  8. How do you find lost commits after a reset or rebase?git reflog

  9. What command removes a file from Git tracking but keeps it on disk?git rm --cached file

  10. How do you safely undo a pushed commit without rewriting history?git revert abc123

Common Gotchas

  • git reset --hard is irreversible for uncommitted work. Always git stash first if you are unsure. There is no reflog entry for changes that were never committed.
  • Rebasing shared branches breaks other people's history. Never rebase commits that have been pushed to a branch others are working on.
  • git add . stages everything, including files you may not want. Prefer git add -p or staging specific files to avoid committing secrets or build artifacts.
  • Forgetting --no-ff on merge loses the branch topology. If you want to preserve that a feature branch existed, use git merge --no-ff.
  • git stash pop drops the stash even if there are conflicts. Use git stash apply instead so you can resolve conflicts without losing the stash entry.

One-Liner Summary

Git is a distributed time machine for your code -- learn reset, revert, rebase, and reflog and you can recover from almost anything.

"What I cannot create, I do not understand." — Richard Feynman