Skip to content
Tutorials Center
My learning

Topics

Lesson 75 of 78 ยท Practice and Review

Git Cheat Sheet

A task-based Git cheat sheet: setup, snapshots, branches, inspection, undo, remotes, rewriting and internals, with decision tables and runnable examples.

A cheat sheet is only useful when you can find the right command in a few seconds. This page is organized by the thing you are trying to do, not by command name: "I want to undo a commit" rather than "git reset". Each group lists the commands you will use most, a short note on when to pick which, and a link to the lesson that explains the details.

At the end you will find decision tables ("which undo do I need?") and a list of safe versus dangerous commands. Four small runnable examples prove the claims that are easiest to get wrong. Everything here is Git 2.56 behavior; older versions may lack git switch and git restore (added in 2.23).

Print this page or keep it open in a tab, then work through the practice problems until you no longer need it.

Setup and configuration

Terminal
git config --global user.name "Ada Lovelace"
git config --global user.email "[email protected]"
git config --global init.defaultBranch main
git config --global pull.ff only          # refuse surprise merges on pull
git config --global rerere.enabled true   # remember conflict resolutions
git config --list --show-origin           # what is set, and where
git init                                  # new repository here
git clone <url> [dir]                     # copy a repository

Configuration lives at three levels: system, global (~/.gitconfig) and local (.git/config). The most specific level wins. See Installing and Configuring Git.

Taking snapshots

Task Command
See what changed git status -sb
Stage a file git add file
Stage parts of a file git add -p file
Stage all tracked changes (no new files) git add -u
Stage everything git add -A
Commit staged changes git commit -m "Subject"
Commit all tracked changes git commit -am "Subject"
Fix the last commit git commit --amend
Unstage a file git restore --staged file
Discard working changes to a file git restore file
Rename or move a tracked file git mv old new
Remove a tracked file git rm file (--cached keeps it on disk)

The staging area is a drafting table: git add copies the current version of a file onto it, and git commit records exactly what is there, not what is in your working tree. More in Staging Changes and Making Good Commits.

Bash Staged versus unstaged: status -sb shows both

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The two-letter code is XY: X is the index compared with HEAD (staged), Y is the working tree compared with the index (unstaged). b.txt shows MM because it has a staged change and a further unstaged change. ?? marks an untracked file.

Branching and merging

Task Command
List branches git branch -vv
Create and switch git switch -c feature
Switch git switch main
Merge feature into the current branch git merge feature
Merge, always with a merge commit git merge --no-ff feature
Merge, only if fast-forward is possible git merge --ff-only feature
Abort a conflicted merge git merge --abort
Replay my commits on top of main git rebase main
Copy one commit onto this branch git cherry-pick <commit>
Delete a merged branch git branch -d feature
Delete an unmerged branch git branch -D feature
Park unfinished work git stash push -u -m "wip"
Bring it back git stash pop
Mark a release git tag -a v1.0 -m "Version 1.0"

See Branches, Merging Branches, Resolving Merge Conflicts, Stashing and Tags.

Inspecting history

Question Command
What happened, compactly? git log --oneline --graph --decorate --all
What did this commit change? git show <commit>
Who wrote this line? git blame -L 10,20 file
Which commits touched this file? git log --follow -- file
Which commits added or removed this string? git log -S"text"
Which commits are on feature but not main? git log main..feature
What differs between the tips? git diff main..feature
What did feature change since it split off? git diff main...feature
What is staged? git diff --staged
Which commit introduced a bug? git bisect start, then good/bad
Where was HEAD before? git reflog

Two dots and three dots mean different things in log and diff. Learn them once in Revision Syntax and Comparing Commits.

Bash Two dots versus three dots

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

git diff main...feature shows only what feature added since the merge base, so it ignores fix.txt. git diff main..feature compares the two tips, so it includes the file main has and feature lacks, shown as a deletion.

Undoing things

Pick the undo by asking where the mistake lives.

Where is the mistake? Safe fix Rewrites history?
Edited a file, not staged git restore file No (but the edit is lost)
Staged by mistake git restore --staged file No
Last commit has a typo or missed file git commit --amend Yes, last commit
Last commit should not exist, keep changes git reset --soft HEAD~1 Yes
Last commit should not exist, drop changes git reset --hard HEAD~1 Yes, and destroys work
Bad commit already pushed or shared git revert <commit> No, adds a new commit
Lost commits after a reset or rebase git reflog, then git reset --hard <old> Moves the branch
Untracked files in the way git clean -nd, then git clean -fd Deletes files for good

The three reset modes differ in how far the move reaches:

TEXT
                  moves branch   resets index   resets working tree
reset --soft          yes             no               no
reset --mixed         yes             yes              no      (default)
reset --hard          yes             yes              yes     (destroys edits)

See Undoing Things, git reset in Depth, Reverting Commits Safely and The Reflog.

Bash The three reset modes side by side

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

After --soft the change is still staged (M., a dot stands for a blank column), after --mixed it is unstaged (.M), and after --hard the file content is back to v1 and nothing is pending. ORIG_HEAD remembers where the branch was before the reset, which is how the loop restores it each round.

Remotes and collaboration

Task Command
List remotes git remote -v
Add a remote git remote add origin <url>
Download without merging git fetch origin
Fetch and drop deleted remote branches git fetch --prune
Fetch and fast-forward the current branch git pull --ff-only
Fetch and rebase git pull --rebase
First push of a branch git push -u origin feature
Later pushes git push
Push after a local rewrite, safely git push --force-with-lease
Delete a remote branch git push origin --delete feature
Push tags git push origin --tags
Sync a fork git fetch upstream && git merge --ff-only upstream/main

fetch never changes your branches; pull is fetch plus a merge or rebase. Prefer --force-with-lease over --force: it refuses to overwrite commits you have not seen. See Remotes, push and pull and Forks and Upstreams.

Rewriting history (only on unshared commits)

Task Command
Edit, reorder, squash the last 4 commits git rebase -i HEAD~4
Squash into an earlier commit automatically git commit --fixup <commit>, then git rebase -i --autosquash
Squash everything since main git reset --soft $(git merge-base main HEAD) then commit
Change author of the last commit git commit --amend --reset-author
Remove a file from all history git filter-branch (or git filter-repo where installed)
Find a bug-introducing commit git bisect run ./test.sh

The golden rule: never rewrite commits other people have already pulled. See Rebasing, Interactive Rebase and Amending, Splitting and Rewriting.

Plumbing and internals

Task Command
Full hash of a revision git rev-parse HEAD
Kind of object git cat-file -t <hash>
Print an object git cat-file -p <hash>
List a tree git ls-tree HEAD
List staged files with blob hashes git ls-files -s
Hash content without storing it git hash-object file
Where is HEAD pointing? git symbolic-ref HEAD
Count loose and packed objects git count-objects -v
Verify the database git fsck
Pack and clean up git gc
Bash Peeking inside with cat-file and ls-tree

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The blob hash depends only on the content (blob 6\0hello\n), so the same file gives the same hash in every repository. Details in Git Objects and References and HEAD.

Safe versus dangerous commands

Most Git commands only add data, so you can always find your way back. A short list can lose work. Learn it by heart.

Safe (read-only or additive) Careful (rewrites or moves things) Dangerous (can destroy uncommitted work or shared history)
status, log, diff, show, blame commit --amend reset --hard
add, commit, switch, branch rebase, rebase -i checkout -- file, restore file (drops edits)
fetch, stash, tag reset --soft/--mixed clean -fd, clean -fdx
revert, cherry-pick branch -D push --force
reflog, bisect stash drop filter-branch, gc --prune=now

Uncommitted edits are the only thing Git cannot bring back, because they were never recorded. Anything that was committed stays reachable from the reflog for at least 30 days by default.

Bash A dry run before git clean

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The -n flag lists what would be deleted without touching anything. Make it a habit: dry run first, then repeat the command with -f.

Decision tables

Merge or rebase?

Situation Choose
Bringing a finished feature into main Merge (--no-ff if you want a visible bubble)
Updating your private branch with the latest main Rebase
The branch is already pushed and others use it Merge
You want a linear history on main Rebase, or squash-merge on the hosting site

Which reset?

You want to... Use
Redo the last commit with the same changes reset --soft HEAD~1
Unstage everything but keep the edits reset (mixed)
Throw everything away and match a commit reset --hard <commit>

Where do I look? Lost a commit: git reflog. Lost an uncommitted edit: nowhere, unless your editor has local history. Lost a stash: git fsck --unreachable | grep commit.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which command stages only some hunks of a file?

    git add -p (patch mode) asks about each hunk so you can stage part of a file and commit only that part.
  2. 2. You pushed a bad commit to a shared branch. What is the safe fix?

    revert does not rewrite history, so nobody who already pulled the bad commit gets a conflicting history.
  3. 3. What does git diff main...feature (three dots) compare?

    Three dots in diff means: start at the common ancestor, so you see only what feature added.
  4. 4. Which of these can permanently destroy uncommitted work?

    reset --hard overwrites the working tree, and edits that were never committed or stashed cannot be recovered from the reflog.
  5. 5. Why prefer push --force-with-lease to push --force?

    The lease checks that the remote branch is still where you last saw it, so you cannot erase a teammate's new commits by accident.

Summary

  • Choose commands by task: snapshot (add, commit), branch (switch, merge, rebase), inspect (log, diff, blame), undo (restore, reset, revert), share (fetch, pull, push).
  • status -sb shows staged and unstaged changes in two columns; diff compares working tree to index, diff --staged index to HEAD.
  • a..b means commits in b not in a; in diff, a...b compares from the merge base.
  • Reset has three modes: soft keeps the index and files, mixed keeps files, hard resets everything.
  • Use revert for shared history, reset or rebase only for private commits, --force-with-lease instead of --force.
  • Always dry-run destructive commands (git clean -n), and remember the reflog is your safety net for committed work.

Next: Practice Problems: Commits, Branches and Merges