Git Cheat Sheet
Quick reference for Git commands, branching strategies, undo operations, and rebase workflows.
Setup & Config
| Command | Description |
|---|---|
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 main | Default branch name |
git config --global pull.rebase true | Rebase on pull by default |
git config --global fetch.prune true | Auto-prune on fetch |
git config --global diff.algorithm histogram | Better diff algorithm |
git config --global push.autoSetupRemote true | First git push sets upstream automatically |
git config --global rerere.enabled true | Remember conflict resolutions and reuse them |
git config --global rebase.autoStash true | Stash/unstash around rebase automatically |
git config --global rebase.updateRefs true | Move stacked branches along when rebasing |
git config --global merge.conflictStyle zdiff3 | Show the common ancestor in conflict markers |
git config --global core.autocrlf input | Convert CRLF to LF on commit (Linux/macOS); use true on Windows |
git config --list --show-origin | Show all config with source |
git config --global --edit | Open global config in editor |
Getting a Repo
| Command | Description |
|---|---|
git init | New 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 -v | List remotes |
git remote add upstream <url> | Add a remote |
git remote set-url origin <url> | Change a remote's URL |
git remote prune origin | Remove stale remote-tracking branches |
Daily Workflow
Basic Commands
| Command | Description |
|---|---|
git status | Show working tree status |
git add file | Stage specific file |
git add -p | Stage 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 --amend | Amend last commit |
git commit --amend --no-edit | Amend without changing message |
git commit --fixup=abc123 | Make a fixup! commit for abc123 (squash later with rebase -i --autosquash) |
git rm file / git mv old new | Delete / rename a tracked file and stage it |
git clean -nd | Dry-run: list untracked files and dirs that would be deleted |
git clean -fd | Delete untracked files and dirs (-x also deletes ignored files) |
git push | Push to remote |
git push -u origin branch | Push and set upstream |
git push --force-with-lease | Force-push, but fail if the remote moved since your last fetch |
git pull | Fetch and merge (or rebase) |
git fetch | Fetch without merging |
git fetch --all --prune | Fetch all remotes, prune deleted |
Branching
| Command | Description |
|---|---|
git branch | List local branches |
git branch -a | List all branches (local + remote) |
git branch feature | Create branch |
git checkout feature | Switch to branch |
git checkout -b feature | Create and switch |
git switch feature | Switch to branch (modern) |
git switch -c feature | Create and switch (modern) |
git switch - | Switch to the previous branch |
git switch -c feature origin/feature | Create local branch tracking a remote one |
git switch --detach abc123 | Check out a commit without a branch |
git branch -vv | Branches with upstream and ahead/behind |
git branch --merged main | Branches already merged into main |
git branch --sort=-committerdate | Branches, most recently committed first |
git branch -u origin/feature | Set upstream of current branch |
git branch -d feature | Delete merged branch |
git branch -D feature | Force delete branch |
git push origin --delete feature | Delete remote branch |
git branch -m old new | Rename branch |
Merge & Rebase
| Command | Description |
|---|---|
git merge feature | Merge feature into current |
git merge --no-ff feature | Merge with merge commit |
git merge --squash feature | Squash all commits, do not commit |
git rebase main | Rebase current onto main |
git rebase --onto main A B | Rebase B onto main from A |
git rebase --continue | Continue after resolving conflicts |
git rebase --abort | Abort rebase |
git rebase --skip | Drop the commit that is conflicting and continue |
git merge --abort | Abort a conflicted merge |
git checkout --ours file / --theirs file | Take one side of a conflict (sides are swapped during a rebase) |
git cherry-pick abc123 | Apply specific commit |
git cherry-pick -x abc123 | Apply commit and note the original hash in the message |
git cherry-pick A..B | Apply commits after A up to and including B (A excluded; use A^..B to include it) |
Viewing History
| Command | Description |
|---|---|
git log --oneline | Compact log |
git log --oneline --graph | Log with branch graph |
git log --oneline -20 | Last 20 commits |
git log --author="Name" | Commits by author |
git log --since="2 weeks ago" | Commits in timeframe |
git log --follow file | File history across renames |
git log -p file | File history with diffs |
git log main..feature | Commits 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:file | History of lines 10-20 of a file |
git log --format="%h %an %ar %s" | Custom one-line format |
git diff | Unstaged changes |
git diff --staged | Staged changes |
git diff main..feature | Diff between the two branch tips |
git diff main...feature | Changes on feature since it forked from main (what a PR shows) |
git diff --word-diff | Word-level diff |
git diff --stat | Summary of changes |
git blame file | Line-by-line attribution |
git blame -w -C file | Blame ignoring whitespace and code moved from other files |
git show abc123 | Show commit details |
git show main:path/file | Show a file as it is on another branch |
git shortlog -sn | Commit count by author |
git grep "text" | Search tracked files (fast) |
git range-diff main old-feature feature | Compare 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
| Scenario | Command | Effect |
|---|---|---|
| Undo last commit, keep changes staged | git reset --soft HEAD~1 | Commit removed, changes staged |
| Undo last commit, keep changes unstaged | git reset HEAD~1 | Commit removed, changes in working tree |
| Undo last commit, discard changes | git reset --hard HEAD~1 | Commit and changes gone |
| Undo a pushed commit (safe) | git revert abc123 | New commit that undoes the changes |
| Undo multiple pushed commits | git revert A..B | Revert range (commits after A up to B) |
| Revert without committing yet | git revert --no-commit A..B | Stage the reverts, commit once |
| Undo a merge commit | git 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
| Command | Description |
|---|---|
git stash | Stash working changes |
git stash -u | Stash including untracked files |
git stash push -m "msg" | Stash with description |
git stash list | List all stashes |
git stash pop | Apply and remove latest stash |
git stash apply | Apply without removing |
git stash apply stash@{2} | Apply specific stash |
git stash drop stash@{0} | Delete specific stash |
git stash clear | Delete all stashes |
git stash show -p | Show stash diff |
git stash push -m "msg" path/ | Stash only some paths |
git stash --staged | Stash only staged changes |
git stash -k | Stash but keep staged changes in the index (--keep-index) |
git stash branch new-branch | Create a branch from a stash and apply it |
Branching Strategies
GitHub Flow (Simple)
Best for: Teams shipping frequently, single production branch.
main ─────●─────●─────●─────●─────
\ /
feature ●───●───●
Rules:
mainis always deployable- Branch from
mainfor features - Open a Pull Request
- Merge to
mainafter review - 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:
mainis the trunk- Feature branches live less than 1 day
- Feature flags for incomplete work
- All commits pass CI before merge
When to Use Which
| Strategy | Team Size | Release Cadence | Complexity |
|---|---|---|---|
| GitHub Flow | 1-10 | Continuous | Low |
| Trunk-Based | 5-100+ | Continuous | Low |
| Git Flow | 5-50 | Scheduled releases | High |
Rebase Workflows
Interactive Rebase
# Rebase last 5 commits
git rebase -i HEAD~5
Commands in the editor:
| Command | Effect |
|---|---|
pick | Keep commit as is |
reword | Keep commit, change message |
edit | Pause to amend commit |
squash | Merge into previous, keep message |
fixup | Merge into previous, discard message |
drop | Remove commit |
exec | Run a shell command after the line above (e.g. exec npm test) |
break | Pause 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
| Aspect | Rebase | Merge |
|---|---|---|
| History | Linear, clean | Preserves branch history |
| Conflicts | Resolved per-commit | Resolved once |
| Safety | Rewrites history | Non-destructive |
| Shared branches | NEVER rebase shared branches | Always safe |
| When | Before merging feature to main | When 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
| Command | Description |
|---|---|
git tag v1.0.0 | Lightweight tag |
git tag -a v1.0.0 -m "Release 1.0.0" | Annotated tag |
git tag -a v1.0.0 abc123 | Tag a specific commit |
git push origin v1.0.0 | Push specific tag |
git push origin --tags | Push all tags |
git tag -d v1.0.0 | Delete local tag |
git push origin --delete v1.0.0 | Delete remote tag |
git tag -l "v1.*" | List tags matching pattern |
Worktrees
| Command | Description |
|---|---|
git worktree add ../hotfix hotfix-branch | Create worktree for branch |
git worktree add -b fix ../fix main | Create new branch fix from main in a new worktree |
git worktree add --detach ../scratch | Worktree on a detached HEAD |
git worktree list | List worktrees |
git worktree remove ../hotfix | Remove worktree |
git worktree prune | Clean 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
| Command | Description |
|---|---|
git sparse-checkout set apps/web libs/ui | Only check out these dirs |
git sparse-checkout add docs | Add a dir |
git sparse-checkout disable | Back to full checkout |
git maintenance start | Schedule background gc/prefetch/commit-graph |
git lfs track "*.psd" | Store matching files in Git LFS (needs git-lfs) |
Submodules
| Command | Description |
|---|---|
git submodule add <url> path | Add a submodule |
git submodule update --init --recursive | Fetch and check out submodules after clone |
git submodule update --remote | Move submodules to their remote branch tip |
Troubleshooting
Common Problems
| Problem | Solution |
|---|---|
| Committed to wrong branch | git reset --soft HEAD~1, switch branch, commit |
| Need to split a commit | git reset HEAD~1, stage and commit in parts |
| Merge conflict on binary file | git checkout --theirs file or --ours |
| Accidentally deleted a branch | git reflog, find the commit, recreate branch |
| Push rejected (non-fast-forward) | git pull --rebase then push |
| Need to force-push after a rebase | git push --force-with-lease (never plain --force on shared branches) |
| Large file accidentally committed | git filter-repo --path big.zip --invert-paths (git filter-branch is discouraged by its own docs) |
| Secret committed and pushed | Rotate the secret first; rewriting history does not un-leak it |
| Wrong author on last commit | git commit --amend --reset-author --no-edit |
| Detached HEAD with new commits | git switch -c new-branch to keep them |
| Need to find which commit introduced a bug | git 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
-
What command stages changes interactively by hunk?
git add -p -
How do you create and switch to a new branch in one command (modern syntax)?
git switch -c feature -
What command undoes the last commit but keeps changes staged?
git reset --soft HEAD~1 -
How do you stash changes including untracked files?
git stash -u -
What command shows commits in branch B that are not in branch A?
git log A..B -
How do you force-delete a branch that has not been merged?
git branch -D feature -
What interactive rebase command merges a commit into the previous one while discarding its message?
fixup -
How do you find lost commits after a reset or rebase?
git reflog -
What command removes a file from Git tracking but keeps it on disk?
git rm --cached file -
How do you safely undo a pushed commit without rewriting history?
git revert abc123
Common Gotchas
git reset --hardis irreversible for uncommitted work. Alwaysgit stashfirst 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. Prefergit add -por staging specific files to avoid committing secrets or build artifacts.- Forgetting
--no-ffon merge loses the branch topology. If you want to preserve that a feature branch existed, usegit merge --no-ff. git stash popkeeps the stash if it hits conflicts. After resolving, rungit stash dropyourself or the entry lingers. On a clean pop the stash is dropped, so usegit stash applyif you want to keep it.--ours/--theirsswap meaning during a rebase. In a rebase, "ours" is the branch you are rebasing onto and "theirs" is your commit being replayed.git push --forceoverwrites teammates' work. Use--force-with-lease(add--force-if-includesto also guard against a background fetch).A..BvsA...B. Ingit log,..means "in B not A" and...means symmetric difference. Ingit diff,A..Bis just the two tips andA...Bdiffs 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.