ToolActToolAct

Git Cheat Sheet

Complete Git command reference, organized by category for quick lookup

All: 65 个命令

Basic Commands(13)

git init

Create a new Git repository in current directory

git clone <url>

Clone a remote repository to local

git clone --depth=1 <url>

Shallow clone, fetch only the latest commit

git add <file>

Add file to staging area

git add .

Add all changes to staging area

git commit -m "message"

Commit staged changes

git commit --amend

Modify the last commit

git status

Show repository current status

git diff

Show unstaged changes

git diff --staged

Show staged changes

git config --list

View all configuration

git config --global user.name "name"

Set global username

git config --global user.email "email"

Set global email

Branch Management(14)

git branch

List all local branches

git branch -a

List all branches (including remote)

git branch <name>

Create new branch

git branch -d <name>

Delete branch

git branch -m <old> <new>

Rename branch

git checkout <branch>

Switch branch

git checkout -b <branch>

Create and switch to new branch

git switch <branch>

Switch branch (Git 2.23+)

git switch -c <branch>

Create and switch to new branch (Git 2.23+)

git merge <branch>

Merge specified branch to current

git merge --no-ff <branch>

Merge branch with merge commit

git rebase <branch>

Rebase current branch onto specified

git rebase --continue

Continue rebase after resolving conflicts

git cherry-pick <commit>

Cherry-pick specific commit to current branch

Remote Operations(10)

git remote -v

View remote repository info

git remote add <name> <url>

Add remote repository

git fetch <remote>

Fetch latest content from remote

git fetch --all

Fetch updates from all remotes

git pull <remote> <branch>

Pull and merge remote branch

git pull --rebase

Pull and rebase

git push <remote> <branch>

Push to remote repository

git push -f

Force push (use with caution)

git push -u origin <branch>

Push and set upstream branch

git push origin --delete <branch>

Delete remote branch

Undo Changes(8)

git reset <file>

Unstage file

git reset --soft HEAD~1

Undo last commit, keep changes

git reset --mixed HEAD~1

Undo commit and staging, keep working directory

git reset --hard HEAD~1

Undo commit and discard all changes

git revert <commit>

Undo specified commit (creates new commit)

git restore <file>

Restore working directory file (Git 2.23+)

git restore --staged <file>

Unstage file (Git 2.23+)

git clean -fd

Remove untracked files and directories

Tag Management(6)

git tag

List all tags

git tag <name>

Create lightweight tag

git tag -a <name> -m "msg"

Create annotated tag

git tag -d <name>

Delete local tag

git push origin <tag>

Push tag to remote

git push --tags

Push all tags to remote

History Viewing(7)

git log

View commit history

git log --oneline

Show compact commit history

git log --oneline --graph --all

Show all branch history graphically

git show <commit>

Show commit details

git blame <file>

Show line-by-line modification history

git reflog

Show all operation history

git bisect start

Start binary search for problem commit

Stash(7)

git stash

Stash current changes

git stash save "message"

Stash changes with message

git stash list

List all stashes

git stash pop

Apply and drop latest stash

git stash apply

Apply latest stash without dropping

git stash drop

Drop latest stash

git stash clear

Clear all stashes

What is Git?

A Git cheat sheet is a quick reference for common version-control commands, grouped by the task you are trying to perform. Git itself is a distributed version control system: every clone contains project history, branches are lightweight pointers, and commits form a record of how a codebase changed over time. The cheat sheet helps when you remember the workflow but not the exact syntax, such as checking staged changes, creating a branch, undoing a commit, stashing work, tagging a release, or synchronizing with a remote. It is a reference, not a substitute for understanding repository state. Destructive commands like reset --hard, clean -fd, rebase, and force push should be copied only after checking uncommitted work, current branch, and remote impact.

Usage Guide

Quick Reference

  1. Click any command card to copy the command
  2. Use search box to quickly find specific commands
  3. Click category tags to filter by type
  4. Hover over commands to see detailed descriptions

Features

Organized by scenarioCommands grouped by basic, branch, remote, undo, tags, history, and stash for easy lookup without scrolling through the entire list.
Search and filterCombine search box and category buttons to quickly narrow down results, perfect when you only remember part of the command or description.
Click to copyClick command card to copy, then replace branch names, file paths, or commit hashes as needed.
Risk warningUndo, reset, and force push commands require confirming impact scope to avoid accidentally deleting local changes or rewriting shared history.

Advanced Tips

  • Use git restore --staged to unstage files
  • Use git commit --amend to modify last commit
  • Use git stash to temporarily save work progress
  • Use git revert to undo pushed commits

Use Cases

Find the command category you need mid-taskSearch or filter Git commands by basic work, branches, remotes, undo, tags, history, and stash so the right syntax is visible without scanning a long article or reopening a tutorial tab. Each card already shows the short description next to the command, which is useful when you remember the workflow but not the exact flags, such as needing --force-with-lease versus --force, or wanting the diff between git restore and git reset.
Copy commands with placeholders intactUse one-click copy for commands such as git checkout -b <branch>, git push -u origin <branch>, git log --oneline --graph --all, or git restore --staged <file>, then replace placeholders in your terminal. Because the reference lives in the browser and no commit data or branch names are sent anywhere, it is safe to copy alongside real hashes, internal branch prefixes, or in-flight feature names that have not been pushed yet.
Review risky commands before using themThe undo section collects reset, clean, restore, and force-push-related workflows so the destructive intent is visible at a glance. Before running git reset --hard HEAD~3 or git push --force, cross-check the current branch with git status and the remote tracking state with git rev-parse --abbrev-ref --symbolic-full-name @{u}, since rewriting shared history still cannot be undone by teammates.
Save branch, tag, and stash snippets as templatesCommands like 'git switch -c feature/x', 'git tag -a v1.2 -m', and 'git stash push -m' repeat across projects with the team's branching or release conventions. Copy them once into the team's onboarding doc, runbook, or pre-commit hook configuration, and revisit whenever Git's behavior changes - for example, when a project requires --force-with-lease in place of plain --force on protected branches.
Use history commands to read the repo, not rewrite itRun 'git log --oneline --graph --all', 'git blame -L', and 'git diff <branch>...' to understand who changed what before opening a rebase or revert. Reading first is cheaper than recovering from a botched history rewrite, especially in monorepos where a stray rebase across feature branches can invalidate dozens of in-progress pull requests.

Technical Principle

Git stores every project state as a content-addressed object graph inside .git/objects, where the address is a 40-character SHA-1 hash (SHA-256 is opt-in since Git 2.29's experimental object format). There are four object types: blob holds raw file bytes, tree maps names to blobs and subtrees, commit points at a tree plus parent commits and author metadata, and tag is a signed pointer to any of the above. Branches and tags under refs/heads/, refs/remotes/, and refs/tags/ are just text files containing a SHA, and HEAD is a symbolic ref that names the current branch.

Local changes flow through three areas: the working directory, the index (also called the staging area, stored in .git/index), and the object database. git add records blob hashes into the index, git commit freezes the index into a new tree plus commit object, and git checkout/switch updates the index and working tree to a target commit. Merges fall into two categories: fast-forward simply advances the branch pointer when the target is a direct descendant, while three-way merges (recursive or ort strategy) compute a common ancestor and build a merge commit with two parents. git rebase rewrites history by replaying commits one-by-one onto a new base, producing new SHAs.

Remote synchronization runs over the HTTPS smart protocol, SSH, or the deprecated git:// protocol, exchanging pack files generated by delta compression. After a fetch, Git stores the snapshot under refs/remotes/origin/* and the reflog under .git/logs/ keeps a 90-day undo trail by default (gc.reflogExpire) so even reset --hard or a botched rebase can be recovered before garbage collection prunes unreachable objects.
  • Object model: blob, tree, commit, tag — content-addressed by SHA-1 (or SHA-256 since 2.29), stored loose under .git/objects/xx/ or packed in .git/objects/pack/*.pack
  • Index/staging: .git/index is a binary file mapping path → blob hash + stat info; git add updates it, git commit freezes it into a tree
  • Refs and HEAD: refs/heads/<branch>, refs/remotes/<remote>/<branch>, refs/tags/<tag> are plain files containing a SHA; HEAD is a symbolic ref to the current branch
  • Merge strategies: fast-forward when target is a descendant, otherwise three-way recursive/ort merge using the merge base; --no-ff forces a merge commit
  • Rebase rewrites: git rebase replays commits onto a new base producing new SHAs, breaking shared history if pushed — hence --force-with-lease is preferred over --force
  • Reflog recovery: .git/logs/HEAD and per-ref logs retain ref movements for 90 days (gc.reflogExpire); git reflog plus git reset restores after destructive operations
  • Transport: smart HTTPS, SSH, or git:// negotiate pack files via the upload-pack/receive-pack protocol; shallow clones use --depth to limit history

Examples

Create and switch to new branch

git checkout -b feature/login  # Create and switch to new branch

Undo working directory changes

git restore filename  # Restore file to last committed state

View commit history

git log --oneline --graph --all  # Graphically show all branch history

FAQ

How do I undo my most recent commit?

git reset --soft HEAD~1 keeps your changes staged so you can recommit; git reset --mixed HEAD~1 keeps them in the working tree but unstaged; git reset --hard HEAD~1 throws them away. If the commit is already pushed, use git revert HEAD instead, which creates a new commit that undoes the change without rewriting history.

What is the difference between git pull and git fetch?

git fetch only downloads commits from the remote into your local refs - it never touches your working branch. git pull is equivalent to git fetch followed by git merge (or git rebase if --rebase is set). Use fetch when you want to inspect upstream changes before integrating them.

How do I discard local changes to a file?

git restore <file> drops uncommitted edits in the working tree; git restore --staged <file> unstages a file without losing its content; git checkout HEAD -- <file> restores the version from the latest commit. For untracked files use git clean -f or -fd to remove directories too.

When should I rebase vs merge?

Rebase when you want a linear history on a private feature branch before merging it back. Merge when integrating a shared branch where preserving the actual development history matters. Never rebase commits that have been pushed to a shared branch unless everyone agrees - it rewrites SHAs and breaks other people's clones.

How do I see what's about to be pushed?

git log @{u}.. shows commits on your branch that are not on the upstream. git diff @{u} shows the combined diff. git status compared to origin (after a fetch) shows ahead/behind counts.

How do I recover a deleted branch or lost commit?

git reflog lists every position HEAD has been at; find the SHA of the commit you lost and run git checkout <sha> or git branch <name> <sha>. Reflog entries last about 90 days by default before garbage collection, so do this soon after the mistake.

What's the safest way to amend a commit?

git commit --amend lets you edit the most recent commit's message or add forgotten files. It rewrites the SHA, so only do it on local commits that have not been pushed. If you must amend a pushed commit, push with --force-with-lease (not --force) to avoid clobbering teammates' updates.