On 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 --global push.autoSetupRemote trueFirst git push sets upstream automatically
git config --global rerere.enabled trueRemember conflict resolutions and reuse them
git config --global rebase.autoStash trueStash/unstash around rebase automatically
git config --global rebase.updateRefs trueMove stacked branches along when rebasing
git config --global merge.conflictStyle zdiff3Show the common ancestor in conflict markers
git config --global core.autocrlf inputConvert CRLF to LF on commit (Linux/macOS); use true on Windows
git config --list --show-originShow all config with source
git config --global --editOpen global config in editor

Getting a Repo

CommandDescription
git initNew repo in current dir
git clone <url>Clone a repo
git clone --depth 1 <url>Shallow clone (latest commit only)
git clone --filter=blob:none <url>Partial clone: full history, blobs fetched on demand
git clone --recurse-submodules <url>Clone with submodules
git remote -vList remotes
git remote add upstream <url>Add a remote
git remote set-url origin <url>Change a remote's URL
git remote prune originRemove stale remote-tracking branches

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 commit --fixup=abc123Make a fixup! commit for abc123 (squash later with rebase -i --autosquash)
git rm file / git mv old newDelete / rename a tracked file and stage it
git clean -ndDry-run: list untracked files and dirs that would be deleted
git clean -fdDelete untracked files and dirs (-x also deletes ignored files)
git pushPush to remote
git push -u origin branchPush and set upstream
git push --force-with-leaseForce-push, but fail if the remote moved since your last fetch
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 switch -Switch to the previous branch
git switch -c feature origin/featureCreate local branch tracking a remote one
git switch --detach abc123Check out a commit without a branch
git branch -vvBranches with upstream and ahead/behind
git branch --merged mainBranches already merged into main
git branch --sort=-committerdateBranches, most recently committed first
git branch -u origin/featureSet upstream of current branch
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 rebase --skipDrop the commit that is conflicting and continue
git merge --abortAbort a conflicted merge
git checkout --ours file / --theirs fileTake one side of a conflict (sides are swapped during a rebase)
git cherry-pick abc123Apply specific commit
git cherry-pick -x abc123Apply commit and note the original hash in the message
git cherry-pick A..BApply commits after A up to and including B (A excluded; use A^..B to include it)

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 log -S "text"Commits that added or removed text (pickaxe)
git log -G "regex"Commits whose diff matches a regex
git log -L 10,20:fileHistory of lines 10-20 of a file
git log --format="%h %an %ar %s"Custom one-line format
git diffUnstaged changes
git diff --stagedStaged changes
git diff main..featureDiff between the two branch tips
git diff main...featureChanges on feature since it forked from main (what a PR shows)
git diff --word-diffWord-level diff
git diff --statSummary of changes
git blame fileLine-by-line attribution
git blame -w -C fileBlame ignoring whitespace and code moved from other files
git show abc123Show commit details
git show main:path/fileShow a file as it is on another branch
git shortlog -snCommit count by author
git grep "text"Search tracked files (fast)
git range-diff main old-feature featureCompare two versions of a rebased branch

Undo Operations

This is the most critical section. Choose carefully.

Undo Staged Changes

# 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

# Discard changes to a file
git restore file

# Discard all working tree changes
git restore .

# Discard hunks interactively
git restore -p file

# Restore a file from another commit/branch (both index and working tree)
git restore --source=main --staged --worktree file

# 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 (commits after A up to B)
Revert without committing yetgit revert --no-commit A..BStage the reverts, commit once
Undo a merge commitgit revert -m 1 <merge-sha>Revert relative to the first parent

Recovery with reflog

# Find lost commits (reset, rebase, amend, deleted branch...)
git reflog                      # HEAD's history
git reflog show feature         # one branch's history

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

# Undo a bad rebase
git reset --hard ORIG_HEAD      # ORIG_HEAD = where HEAD was before rebase/reset/merge

# Recover a deleted branch
git reflog
git switch -c recovered abc123  # or: git checkout -b recovered abc123

# Commits that are not in any reflog (e.g. a dropped stash)
git fsck --lost-found

Reflog is local only and entries expire (default 90 days, 30 for unreachable commits).

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
git stash push -m "msg" path/Stash only some paths
git stash --stagedStash only staged changes
git stash -kStash but keep staged changes in the index (--keep-index)
git stash branch new-branchCreate a branch from a stash and apply it

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

# 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
execRun a shell command after the line above (e.g. exec npm test)
breakPause here; resume with git rebase --continue

To reorder commits, move the lines; there is no reorder command.

Common Rebase Patterns

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

# Squash fixup commits
# Mark fixup commits as "fixup" in the editor
# Or let git do it: create them with --fixup, then
git commit --fixup=abc123
git rebase -i --autosquash main

# Run tests on every commit of the branch
git rebase -i --exec "npm test" main

# 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 add -b fix ../fix mainCreate new branch fix from main in a new worktree
git worktree add --detach ../scratchWorktree on a detached HEAD
git worktree listList worktrees
git worktree remove ../hotfixRemove worktree
git worktree pruneClean up worktrees whose dirs were deleted manually

Use worktrees to work on multiple branches simultaneously without stashing. A branch can be checked out in only one worktree at a time.


Bisect

git bisect start
git bisect bad                  # current commit is broken
git bisect good v1.0            # this one was fine
# git checks out a midpoint; test it, then mark:
git bisect good                 # or: git bisect bad / git bisect skip
# ...repeat until git prints the first bad commit
git bisect reset                # back to where you started

# Automate: script exits 0 = good, 1-124 = bad, 125 = skip
git bisect start HEAD v1.0
git bisect run npm test

Sparse Checkout & Large Repos

CommandDescription
git sparse-checkout set apps/web libs/uiOnly check out these dirs
git sparse-checkout add docsAdd a dir
git sparse-checkout disableBack to full checkout
git maintenance startSchedule background gc/prefetch/commit-graph
git lfs track "*.psd"Store matching files in Git LFS (needs git-lfs)

Submodules

CommandDescription
git submodule add <url> pathAdd a submodule
git submodule update --init --recursiveFetch and check out submodules after clone
git submodule update --remoteMove submodules to their remote branch tip

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
Need to force-push after a rebasegit push --force-with-lease (never plain --force on shared branches)
Large file accidentally committedgit filter-repo --path big.zip --invert-paths (git filter-branch is discouraged by its own docs)
Secret committed and pushedRotate the secret first; rewriting history does not un-leak it
Wrong author on last commitgit commit --amend --reset-author --no-edit
Detached HEAD with new commitsgit switch -c new-branch to keep them
Need to find which commit introduced a buggit bisect start, git bisect bad, git bisect good v1.0

.gitignore Not Working

# 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

git config --global alias.sw switch
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 keeps the stash if it hits conflicts. After resolving, run git stash drop yourself or the entry lingers. On a clean pop the stash is dropped, so use git stash apply if you want to keep it.
  • --ours / --theirs swap meaning during a rebase. In a rebase, "ours" is the branch you are rebasing onto and "theirs" is your commit being replayed.
  • git push --force overwrites teammates' work. Use --force-with-lease (add --force-if-includes to also guard against a background fetch).
  • A..B vs A...B. In git log, .. means "in B not A" and ... means symmetric difference. In git diff, A..B is just the two tips and A...B diffs from the merge base.

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.