Skip to main content

Git Cheatsheet — 100+ Commands with Pitfalls and Real Examples

Git command cheat sheet — searchable, with explanations, common mistakes, and real examples.

  • Runs locally
  • Category Developer & DevOps
  • Best for Formatting, validating, shrinking, or inspecting code-adjacent text.
102 commands
Basic (16)
git init

Create a new empty git repository in the current directory.

Common pitfall: Running inside an existing repo creates a nested .git that confuses tooling. Run `git status` first.

Examples
git init
git init my-project
git clone <url>

Download a remote repository into a new local directory, with full history.

Common pitfall: For huge repos use --depth=1 (shallow) to skip history; you cannot push amends from a shallow clone without --unshallow.

Examples
git clone https://github.com/user/repo.git
git clone --depth=1 https://github.com/user/repo.git
git status

Show changed, staged and untracked files in the working tree.

Examples
git status
git status -s
git add <file>

Stage a file (or all files with .) for the next commit.

Common pitfall: `git add .` from a subdirectory only adds that subtree; `git add -A` stages everything in the repo including deletions.

Examples
git add src/index.ts
git add .
git add -A
git add -p
git commit -m "msg"

Record staged changes as a new commit with the given message.

Common pitfall: Forgetting to stage first creates an empty commit error; -am only stages tracked files (not new files).

Examples
git commit -m "fix: handle null user"
git commit -am "wip"
git commit --amend

Replace the last commit with a new one (message and/or content).

Common pitfall: Amending a pushed commit rewrites history — collaborators need to force-pull or face conflicts.

Examples
git commit --amend
git commit --amend --no-edit
git commit --amend -m "better message"
git push

Upload local commits on the current branch to the tracked remote.

Examples
git push
git push origin main
git push -u origin <branch>

Push a new local branch to the remote and set it as the upstream tracking branch.

Common pitfall: Without -u, future `git push` on this branch will keep asking for the remote/branch.

Examples
git push -u origin feature/login
git pull

Fetch changes from the tracked remote branch and merge them into the current branch.

Common pitfall: Default pull = fetch + merge, which creates merge commits. Many teams prefer `git pull --rebase`.

Examples
git pull
git pull --rebase
git fetch

Download new commits, refs and objects from a remote, but do NOT merge anything into your branches.

Examples
git fetch
git fetch origin
git fetch --all --prune
git clone --depth=1 <url>

Shallow clone with only the latest commit (no history). Much faster for CI builds.

Common pitfall: Cannot push or rebase from a shallow clone until you run `git fetch --unshallow`.

Examples
git clone --depth=1 https://github.com/torvalds/linux.git
git mv <src> <dst>

Rename or move a file and stage the change in one step.

Examples
git mv old-name.ts new-name.ts
git log -n 5

Show only the last 5 commits (any number works).

Examples
git log -n 5
git log -3 --oneline
git tag <name>

Create a lightweight tag on the current commit. Use -a for an annotated tag with message + tagger.

Common pitfall: Annotated tags (`git tag -a v1.0 -m "..."`) are recommended for releases — lightweight tags do not store metadata.

Examples
git tag v1.0.0
git tag -a v1.0.0 -m "first stable release"
git tag -d <name>

Delete a local tag. To delete the remote tag too: `git push --delete origin <name>`.

Examples
git tag -d v1.0.0
git push --delete origin v1.0.0
git rm <file>

Remove a file from the working tree AND stage the deletion.

Common pitfall: Use `git rm --cached <file>` to stop tracking without deleting from disk (e.g. for files newly added to .gitignore).

Examples
git rm secret.env
git rm --cached config.local.json
Branch (16)
git branch

List local branches; * marks the current branch.

Examples
git branch
git branch -a
git branch -vv
git branch <name>

Create a new branch from the current HEAD, but do not switch to it.

Examples
git branch feature/login
git branch -d <name>

Delete a local branch (safely — fails if it has unmerged commits).

Common pitfall: Use -D (capital) to force-delete unmerged branches — irreversible without reflog.

Examples
git branch -d feature/done
git branch -D feature/wip
git branch -m <new>

Rename the current branch.

Examples
git branch -m main
git branch -m old-name new-name
git checkout <branch>

Switch to an existing branch (legacy command — git switch is the modern replacement).

Common pitfall: `git checkout <file>` and `git checkout <branch>` are different commands sharing one name — confusing. Use `git switch` and `git restore`.

Examples
git checkout main
git checkout -
git checkout -b <new>

Create a new branch from current HEAD and switch to it in one step.

Examples
git checkout -b feature/login
git checkout -b hotfix origin/main
git switch <branch>

Switch to an existing branch. Modern replacement for `git checkout <branch>`.

Examples
git switch main
git switch -
git switch -c <new>

Create and switch to a new branch. Modern replacement for `git checkout -b`.

Examples
git switch -c feature/login
git switch -c hotfix origin/main
git merge <branch>

Merge the named branch into the current branch.

Common pitfall: Default merge creates a merge commit even when fast-forward is possible. Use `--ff-only` to refuse non-FF merges or `--no-ff` to always make a merge commit.

Examples
git merge feature/login
git merge --no-ff feature/login
git merge --ff-only origin/main
git merge --abort

Cancel an in-progress merge and restore the pre-merge state.

Examples
git merge --abort
git rebase <branch>

Replay commits from current branch on top of <branch>. Linear history, but rewrites commit IDs.

Common pitfall: Never rebase commits already pushed to a shared branch — collaborators will get conflicts on every pull.

Examples
git rebase main
git rebase origin/main
git rebase --abort

Cancel an in-progress rebase and restore the pre-rebase state.

Examples
git rebase --abort
git rebase --continue

After resolving conflicts during rebase, continue replaying remaining commits.

Examples
git add resolved-file.ts && git rebase --continue
git cherry-pick <sha>

Apply the changes from a specific commit onto the current branch as a new commit.

Common pitfall: The cherry-picked commit gets a NEW SHA. Cherry-picking the same change twice creates duplicate logic.

Examples
git cherry-pick a1b2c3d
git cherry-pick a1b2c3d..f4e5d6c
git cherry-pick -x a1b2c3d
git branch -a

List ALL branches (local + remote-tracking).

Examples
git branch -a
git branch --merged

List local branches fully merged into the current branch — safe to delete.

Examples
git branch --merged main
git branch --merged | grep -v "\*" | xargs git branch -d
Undo / recovery (13)
git reset HEAD <file>

Unstage a file (keep changes in the working tree).

Examples
git reset HEAD src/index.ts
git reset HEAD .
git reset --soft HEAD~1

Undo the last commit but keep changes staged. The most "non-destructive" reset.

Examples
git reset --soft HEAD~1
git reset --mixed HEAD~1

Undo the last commit and unstage everything, but keep working tree changes. This is the default.

Examples
git reset HEAD~1
git reset --mixed HEAD~1
git reset --hard HEAD~1

Throw away the last commit AND wipe matching working tree changes. Destructive.

Common pitfall: Anything not committed AND not in reflog is gone. Run `git stash` first if you might want it back.

Examples
git reset --hard HEAD~1
git reset --hard origin/main
git revert <sha>

Create a new commit that undoes the changes of <sha>. Safe on shared branches — does NOT rewrite history.

Examples
git revert a1b2c3d
git revert HEAD
git revert -m 1 <merge-sha>
git restore <file>

Discard unstaged changes in a file (modern replacement for `git checkout -- <file>`).

Examples
git restore src/broken.ts
git restore .
git restore --staged <file>

Unstage a file but keep working tree changes (modern replacement for `git reset HEAD <file>`).

Examples
git restore --staged src/index.ts
git stash

Save uncommitted changes (staged + unstaged) onto a stack and reset the working tree.

Common pitfall: By default `git stash` does NOT include untracked files; use `git stash -u` to include them.

Examples
git stash
git stash -u
git stash push -m "WIP login form"
git stash pop

Re-apply the most recent stash AND remove it from the stash stack.

Common pitfall: If pop has conflicts the stash stays on the stack — fix conflicts then `git stash drop`.

Examples
git stash pop
git stash pop stash@{2}
git stash list

List all stashes with their indexes and messages.

Examples
git stash list
git stash drop

Delete a single stash without applying it.

Examples
git stash drop
git stash drop stash@{1}
git reflog

Show local history of HEAD movements. Lifesaver for recovering lost commits / branches.

Common pitfall: Reflog is LOCAL ONLY — pushing/cloning does not copy it. Default expiry is 90 days.

Examples
git reflog
git reset --hard HEAD@{1}
git clean -fd

Delete untracked files (-f) and untracked directories (-d) from the working tree.

Common pitfall: Irreversible. Always `git clean -nfd` (dry-run) first to see what will be deleted.

Examples
git clean -nfd
git clean -fd
git clean -fdx
Remote (10)
git remote -v

List all remotes with their fetch and push URLs.

Examples
git remote -v
git remote add <name> <url>

Add a new remote under the given short name (usually `origin` or `upstream`).

Examples
git remote add origin https://github.com/me/repo.git
git remote add upstream https://github.com/orig/repo.git
git remote set-url <name> <url>

Change the URL of an existing remote (e.g. switching from HTTPS to SSH).

Examples
git remote set-url origin git@github.com:me/repo.git
git remote rename <old> <new>

Rename a remote.

Examples
git remote rename origin github
git remote remove <name>

Remove a remote entirely (does NOT delete the remote repo itself).

Examples
git remote remove old-upstream
git fetch --prune

Fetch from remote AND delete local remote-tracking branches whose remote counterparts are gone.

Examples
git fetch --prune
git fetch -p origin
git pull --rebase

Fetch from remote and rebase local commits on top — keeps history linear, avoids merge commits.

Common pitfall: If you have unrelated remote changes and rebase fails, run `git rebase --abort` to back out.

Examples
git pull --rebase
git config --global pull.rebase true
git push --tags

Push local tags to the remote (regular push does not include them).

Examples
git push --tags
git push origin v1.2.0
git push --delete origin <branch>

Delete a branch on the remote.

Examples
git push --delete origin feature/old
git push origin :feature/old
git ls-remote <url>

List refs (branches, tags) on a remote WITHOUT cloning. Handy for inspecting a repo before downloading.

Examples
git ls-remote https://github.com/torvalds/linux.git
git ls-remote --heads origin
Collaboration (9)
git push --force-with-lease

Force-push, but ONLY if the remote tip is what you last saw. The safe force-push.

Common pitfall: Plain --force overwrites teammates work silently. Always use --force-with-lease on shared branches.

Examples
git push --force-with-lease
git push --force-with-lease origin feature/login
git rebase -i HEAD~N

Interactively rewrite the last N commits: reorder, squash, fixup, reword, drop.

Common pitfall: Rebasing pushed commits = history rewrite. Only do it on your own branches before PR.

Examples
git rebase -i HEAD~5
git rebase -i main
git commit --fixup=<sha>

Create a fixup commit targeting <sha>. With `git rebase -i --autosquash` it auto-squashes into the right spot.

Examples
git commit --fixup=a1b2c3d
git rebase -i --autosquash main
git merge --squash <branch>

Squash all commits of <branch> into one staged change without committing — you then write one summary commit.

Examples
git merge --squash feature/login
git commit -m "feat: login flow"
git format-patch <branch>

Generate .patch files for each commit since <branch>. Used to mail patches to mailing lists (Linux kernel style).

Examples
git format-patch main
git format-patch -1 HEAD
git am <patch>

Apply a mailbox-style patch (created by format-patch) as one or more commits.

Examples
git am 0001-fix-bug.patch
git request-pull <start> <url>

Generate a summary of changes for asking an upstream maintainer to pull from you (pre-GitHub workflow).

Examples
git request-pull v1.0 https://github.com/me/repo feature-x
git pull --rebase --autostash

Auto-stash dirty working tree, pull --rebase, then unstash. Great alias for the daily pull.

Examples
git pull --rebase --autostash
git config --global rebase.autoStash true
git worktree add <path> <branch>

Check out an additional branch into a separate working directory — work on two branches without stashing.

Common pitfall: Worktrees share the same .git, so reflog / index ops still affect each other. List with `git worktree list`.

Examples
git worktree add ../hotfix hotfix/login
git worktree list
git worktree remove ../hotfix
Config & aliases (9)
git config --global user.name "Name"

Set your global git author name (applies to all repos).

Examples
git config --global user.name "Alice Wang"
git config --global user.email "you@example.com"

Set your global git author email.

Common pitfall: Use a per-repo `git config user.email` inside work repos to keep personal/work commit attribution separate.

Examples
git config --global user.email "alice@company.com"
git config user.email "alice@personal.com"
git config --list

Show every effective config setting (system + global + local), in evaluation order.

Examples
git config --list
git config --list --show-origin
git config --global alias.<name> <cmd>

Create a custom git alias. Common ones: co=checkout, br=branch, st=status, lg="log --oneline --graph".

Examples
git config --global alias.co checkout
git config --global alias.lg "log --oneline --graph --all"
git config --global core.editor "code --wait"

Set the editor git opens for commit messages, interactive rebase, etc.

Examples
git config --global core.editor "code --wait"
git config --global core.editor "vim"
git config --global init.defaultBranch main

Make `git init` create `main` as the default branch instead of `master`.

Examples
git config --global init.defaultBranch main
git config --global pull.rebase true

Make `git pull` always rebase by default (no more accidental merge commits).

Examples
git config --global pull.rebase true
git config --global core.autocrlf input

Convert CRLF to LF on commit but not on checkout. Recommended on macOS/Linux working with cross-platform repos.

Common pitfall: On Windows the recommended value is `true` (CRLF on checkout, LF on commit). Mixing them creates phantom diffs.

Examples
git config --global core.autocrlf input
git config --unset <key>

Remove a single git config entry.

Examples
git config --global --unset user.email
git config --unset alias.co
Inspect & history (16)
git log

Show commit history for the current branch.

Examples
git log
git log -n 10
git log --author="Alice"
git log --oneline --graph --all

Compact, one-line-per-commit graph of every branch — the most-used git log incantation.

Examples
git log --oneline --graph --all
git log --oneline --graph --all --decorate
git log -p

Show commit history WITH the full diff of each commit.

Examples
git log -p
git log -p src/index.ts
git log --stat

Show commit history with file-change statistics (which files, how many lines).

Examples
git log --stat
git log --stat -n 5
git diff

Show unstaged changes (working tree vs index).

Examples
git diff
git diff src/index.ts
git diff --staged

Show staged changes (index vs last commit) — what `git commit` would record.

Examples
git diff --staged
git diff --cached
git diff <branch1>..<branch2>

Show the diff between the tips of two branches.

Examples
git diff main..feature/login
git diff origin/main..HEAD
git diff <branch1>...<branch2>

Show changes on <branch2> since it diverged from <branch1> (uses merge base). Common for PR previews.

Common pitfall: Two dots vs three dots produce different diffs — three-dot is what PRs actually show.

Examples
git diff main...feature/login
git blame <file>

Show, for every line of a file, the commit and author that last changed it.

Common pitfall: Whitespace-only / formatting commits hide real authors. Use `git blame -w --ignore-rev <fmt-sha>` to skip them.

Examples
git blame src/index.ts
git blame -L 10,30 src/index.ts
git blame -w src/index.ts
git show <sha>

Show metadata and diff of a single commit.

Examples
git show a1b2c3d
git show HEAD
git show HEAD:src/index.ts
git shortlog -sn

Summarize commits per author with counts (sorted, numbered). Great for changelogs / credits.

Examples
git shortlog -sn
git shortlog -sn --since="1 month ago"
git bisect

Binary-search through commits to find the one that introduced a bug.

Examples
git bisect start
git bisect bad
git bisect good v1.0
git bisect reset
git log -S "<text>"

Find every commit that ADDED or REMOVED the given text — invaluable for "when did this string appear?".

Examples
git log -S "TODO" --source --all
git log -S "DEBUG_FLAG"
git grep <pattern>

Search tracked files for a regex pattern (faster and ignore-aware vs plain grep).

Examples
git grep "TODO"
git grep -n "TODO" -- "*.ts"
git diff --name-only

List ONLY the file names that changed, no diff body. Useful for piping to other commands.

Examples
git diff --name-only
git diff --name-only origin/main...HEAD | xargs eslint
git log --since/--until

Filter commits by date range. Accepts natural language like "2 weeks ago" or ISO dates.

Examples
git log --since="2 weeks ago"
git log --since=2026-01-01 --until=2026-02-01
Submodules (6)
git submodule add <url> <path>

Add another git repo as a submodule at the given path.

Common pitfall: Submodules pin a specific commit, not a branch. New clones need `git submodule update --init --recursive` or the dir will be empty.

Examples
git submodule add https://github.com/user/lib.git vendor/lib
git submodule init

Register submodules listed in .gitmodules into local .git/config.

Examples
git submodule init
git submodule update --init --recursive

Initialize, fetch and check out all submodules (and submodules-of-submodules) to their pinned commits.

Examples
git submodule update --init --recursive
git clone --recurse-submodules <url>
git submodule update --remote

Move each submodule to the latest commit of its tracked remote branch (then commit in the parent).

Examples
git submodule update --remote
git submodule update --remote vendor/lib
git submodule foreach <cmd>

Run a shell command inside every submodule. Useful for batch git operations.

Examples
git submodule foreach git pull
git submodule foreach "git checkout main && git pull"
git submodule deinit <path>

Remove a submodule cleanly: unregister it, then `git rm <path>` and commit.

Common pitfall: Just deleting the directory leaves stale .gitmodules / .git/config entries. Always deinit + rm.

Examples
git submodule deinit vendor/lib
git rm vendor/lib && rm -rf .git/modules/vendor/lib
Common mistakes (7)
git checkout -- <file> (LEGACY — destructive)

Discard ALL unstaged changes in <file>. Same as `git restore <file>`. Cannot be undone — there is no reflog for working-tree state.

Common pitfall: No prompt, no confirmation, no backup. Use `git stash` first if unsure.

Examples
git checkout -- broken.ts
git restore broken.ts
detached HEAD recovery

You checked out a commit/tag directly (e.g. `git checkout v1.0`). Any commits you make here will be lost unless you create a branch.

Common pitfall: If you accidentally left detached HEAD with new commits, find them in `git reflog` and `git branch save-me <sha>` immediately.

Examples
git switch -c new-branch
git reflog
git branch save-me HEAD@{0}
merge conflict resolution

When git stops mid-merge with conflicts: edit the <<<<<<< / ======= / >>>>>>> markers in each file, `git add` each resolved file, then `git commit` (or `git merge --continue`).

Common pitfall: Forgetting to `git add` the resolved file leaves the merge incomplete — commit will fail with "you have unmerged paths".

Examples
git status
git add resolved.ts
git commit
git merge --abort
recover lost commits with reflog

After a botched reset/rebase/branch-delete, `git reflog` lists every HEAD movement. Find the SHA you want and `git reset --hard <sha>` or `git branch rescue <sha>`.

Common pitfall: Reflog entries expire (default 90 days for reachable, 30 days for unreachable). Recover sooner rather than later.

Examples
git reflog
git branch rescue HEAD@{3}
git reset --hard HEAD@{5}
undo `git push --force`

If you force-pushed and overwrote teammates work: ask them to share their reflog (their local copy still has the old commits) and force-push that SHA back.

Common pitfall: GitHub keeps "lost" commits on its dangling-objects GC for ~14 days — you can sometimes recover via the API. ALWAYS use --force-with-lease.

Examples
# on a teammate's machine still holding the old SHAs:
git push --force-with-lease origin <sha>:main
remove a file from git history

A secret got committed. `git rm` only removes it going forward. To purge ALL history, use `git filter-repo` (modern, preferred) or BFG Repo Cleaner.

Common pitfall: After purge, rotate the secret anyway — anyone who cloned still has it. Then force-push the cleaned history.

Examples
git filter-repo --invert-paths --path secrets/key.pem
git push --force-with-lease origin --all
"fatal: refusing to merge unrelated histories"

You tried to merge/pull two repos that have no common ancestor (e.g. cloned and re-inited). Add `--allow-unrelated-histories` if you really want to merge them.

Examples
git pull origin main --allow-unrelated-histories

What this tool does

Searchable git command cheat sheet covering 100+ commands you actually type at the terminal. Every entry has the full syntax, a plain-English and Chinese explanation, the common pitfall people hit with it, and one or two real examples you can copy. Nine categories: basic (init, clone, status, add, commit, push, pull, fetch, tag, mv, rm), branch (branch, checkout, switch, merge, rebase, cherry-pick), undo & recovery (reset --soft / --mixed / --hard, revert, restore, stash, reflog, clean), remote (remote, fetch --prune, push -u, push --tags), collab (rebase -i, --autosquash, merge --squash, --force-with-lease, worktree), config & aliases, inspect & history (log, diff, blame, show, bisect, grep, log -S), submodules (add, init, update --remote, foreach, deinit), and common mistakes (detached HEAD recovery, merge conflict workflow, lost-commit recovery via reflog, undoing --force-push, purging secrets with filter-repo). Type any word and it filters live across commands, descriptions, pitfalls and examples; tap a category chip to scope. Bilingual EN/ZH, fully client-side, no tracking, no ads. Pair with our Regex Cheatsheet for the other "I always forget this syntax" reference, or Crontab Helper for the third thing every developer Googles weekly.

Tool details

Input
Files
The page exposes text boxes, numeric controls, file pickers, or structured inputs depending on the tool.
Output
Live result + Copy + Download
The result area focuses on usable output, with copy, download, or preview actions when supported.
Privacy
Browser-side processing
The main tool logic does not call an external API, so inputs normally stay in the current tab.
Save / share
No account required
Open the page and use it; whether results survive refresh depends on the tool.
Performance budget
Initial JS <= 25 KB
No WASM budget is declared, keeping the tool quick to open on mobile.
Best fit
Developer & DevOps · Developer
Category and role tags drive related tools, internal links, and quick fit checks.

How to use

  1. 1. Input

    Paste or drop your content into the tool panel.

  2. 2. Process

    Click the button. All processing is local in your browser.

  3. 3. Copy / Download

    Copy the result or download to disk in one click.

How Git Cheatsheet fits into your work

Use it in the small gaps between coding, reviewing, debugging, and shipping.

Developer jobs

  • Formatting, validating, shrinking, or inspecting code-adjacent text.
  • Preparing snippets for documentation, tickets, commits, or handoff.
  • Checking a small payload quickly without switching tools.

Developer checks

  • Run irreversible transforms like minify or obfuscate on a copy.
  • Keep secrets out of pasted snippets unless the tool explicitly stays local.
  • Use your normal tests or linter before shipping transformed code.

Good next steps

These links move the current task into a more complete workflow.

  1. 1 .gitignore Generator Pick your stack — Node, Python, Go, Docker, macOS, VS Code — and get a deduped, sectioned .gitignore. Browser-only. Open
  2. 2 Regex Cheatsheet Interactive regex cheat sheet — quick reference for every flavor (JS, Python, PCRE). Open
  3. 3 Crontab Helper — Visual Builder & Explainer Visual crontab builder + human-readable explanation + next run preview. Open

FAQ

Tool combos

Folks in your role tend to reach for these alongside this tool.

Made by Toolora · 100% client-side · Updated 2026-05-29