Git Cheatsheet
Every Git command you need for daily development: from init to advanced history rewriting, with syntax and real use cases.147 commands · 10 sections
Git is the industry-standard version control system. This cheatsheet covers every command across the full Git workflow: creating and cloning repositories, staging and committing changes, branching and merging, collaborating with remotes, inspecting history, stashing work, and undoing mistakes.
Every command shows its real syntax followed by the use case: when and why you reach for it. Commands are grouped by workflow stage so you can find what you need quickly.
Setup & Config15
git config --global user.name "Name"git config --global user.email "email"git config --global init.defaultBranch maingit config --global core.editor "code --wait"git config --global core.autocrlf inputgit config --global pull.rebase truegit config --global alias.co checkoutgit config --global alias.lg "log --oneline --graph --decorate --all"git config --listgit config --global --unset user.emailgit config core.sshCommand "ssh -i ~/.ssh/deploy_key"git config --global credential.helper storegit config --global diff.tool vscodegit config --global merge.tool vscodegit config --global core.excludesfile ~/.gitignore_globalRepositories8
git initgit init --bare repo.gitgit clone <url>git clone --depth 1 <url>git clone --branch <tag> <url>git clone --recurse-submodules <url>git statusgit status --shortStaging & Committing16
git add <file>git add .git add -pgit add -ugit commit -m "message"git commit -am "message"git commit --amendgit commit --amend --no-editgit commit --fixup=<commit>git commit --squash=<commit>git diffgit diff --stagedgit diff <file>git diff HEADgit diff --statgit diff main...featureBranching & Merging20
git branchgit branch -agit branch -vvgit branch <name>git switch -c <name>git switch <name>git switch -git checkout <file>git branch -d <name>git merge <branch>git merge --no-ff <branch>git merge --abortgit rebase <branch>git rebase -i HEAD~ngit rebase -i --autosquash HEAD~ngit rebase --continuegit rebase --abortgit cherry-pick <commit>git cherry-pick -n <commit>git merge --squash <branch>Inspecting & Comparing20
git loggit log --onelinegit log --oneline --graph --allgit log --oneline -n 10git log --author="jane" --onelinegit log --since="2 weeks ago" --onelinegit log --grep="fix:" --onelinegit log -p <file>git log -S "string" --onelinegit log -G "regex" --onelinegit blame <file>git show <commit>git show HEADgit show HEAD~1:path/to/filegit refloggit diff HEAD~1 HEADgit shortlog -sngit count-objects -vHgit rev-parse HEADgit describe --tagsUndoing Changes15
git restore <file>git restore --staged <file>git restore --source=HEAD~1 <file>git reset --soft HEAD~1git reset HEAD~1git reset --hard HEAD~1git reset --hard <commit>git revert <commit>git revert -n <commit>git clean -fdgit clean -fdXgit update-ref -d HEADgit bisect start && git bisect bad && git bisect good <commit>git bisect run <script>git bisect resetRemote Collaboration21
git remote -vgit remote add origin <url>git remote rename <old> <new>git remote set-url origin <url>git remote remove <name>git fetch origingit fetch --prune origingit pullgit pull --rebasegit pushgit push -u origin <branch>git push --force-with-leasegit push origin --delete <branch>git push --tagsgit push --all origingit ls-remote origingit submodule add <url> <path>git submodule update --init --recursivegit worktree add ../hotfix maingit worktree listgit request-pull origin main https://github.com/user/repoStashing12
git stashgit stash push -m "message"git stash push <file>git stash --keep-indexgit stash listgit stash applygit stash popgit stash show -p stash@{1}git stash drop stash@{0}git stash cleargit stash branch <name>git stash -uTags & Releases10
git taggit tag v1.0.0git tag -a v1.0.0 -m "Release v1.0.0"git tag -a v1.0.0 <commit>git tag -d v1.0.0git push origin --delete v1.0.0git checkout v1.0.0git show v1.0.0git log v1.0.0..v2.0.0 --onelinegit tag --contains <commit>Advanced History10
git gcgit gc --aggressive --prune=nowgit fsck --lost-foundgit filter-branch --force --index-filter "git rm --cached --ignore-unmatch .env" --prune-empty -- --allgit replace <old> <new>git archive --format=zip -o release.zip HEADgit apply <patchfile>git format-patch -1 HEADgit subtree add --prefix=lib <url> <branch>git subtree pull --prefix=lib <url> <branch>Git Cheatsheet
Every Git command you need for daily development: from init to advanced history rewriting, with syntax and real use cases.
Git is the industry-standard version control system. This cheatsheet covers every command across the full Git workflow: creating and cloning repositories, staging and committing changes, branching and merging, collaborating with remotes, inspecting history, stashing work, and undoing mistakes.
Every command shows its real syntax followed by the use case: when and why you reach for it. Commands are grouped by workflow stage so you can find what you need quickly.
Setup & Config
git config --global user.name "Name": Set your Git username globally: required before your first commit.git config --global user.email "email": Set the email attached to every commit. Match your GitHub/GitLab account.git config --global init.defaultBranch main: Use main as the default branch name for every new repository instead of master.git config --global core.editor "code --wait": Set your editor for commit messages and interactive rebases: VS Code opens and waits for you to save.git config --global core.autocrlf input: Prevent CRLF/LF line-ending noise on cross-platform teams (use input on macOS/Linux, true on Windows).git config --global pull.rebase true: Rebase your local commits on top of pulled changes instead of creating merge commits.git config --global alias.co checkout: Create a shorthand alias: type git co instead of git checkout.git config --global alias.lg "log --oneline --graph --decorate --all": Define a pretty one-line history graph you will actually use daily.git config --list: Show every resolved config value: system, global, and local: to debug weird Git behavior.git config --global --unset user.email: Remove a config key when it is wrong or no longer needed.git config core.sshCommand "ssh -i ~/.ssh/deploy_key": Use a specific SSH key for one repository: essential when you manage multiple GitHub accounts.git config --global credential.helper store: Cache credentials in plain text so Git stops asking for your password on every push.git config --global diff.tool vscode: Set a difftool so git difftool opens your editor for side-by-side diffs.git config --global merge.tool vscode: Set a mergetool that opens your editor's merge view to resolve conflicts visually.git config --global core.excludesfile ~/.gitignore_global: Point to a global gitignore for files you never want tracked in any repo (.DS_Store, Thumbs.db).Repositories
git init: Create a new empty repository in the current directory.git init --bare repo.git: Create a bare repository: no working tree: for a central server or remote you never edit directly.git clone <url>: Copy an existing remote repository to your machine with full history.git clone --depth 1 <url>: Shallow clone: only the latest commit. Use for CI, deployment, or huge repos.git clone --branch <tag> <url>: Clone and check out a specific branch or tag immediately.git clone --recurse-submodules <url>: Clone a repo and initialize all its submodules in one step.git status: Show the working tree state: modified, staged, and untracked files. Run it constantly.git status --short: Compact one-line-per-file status output: perfect for terminal muscle memory.Staging & Committing
git add <file>: Stage a file: mark it to be included in the next commit.git add .: Stage every change in the current directory (including deletions).git add -p: Stage changes interactively hunk-by-hunk: keep unrelated edits out of a commit.git add -u: Stage only modified and deleted tracked files: never new untracked files.git commit -m "message": Create a commit from staged changes with a message.git commit -am "message": Stage all tracked changes and commit in one step (untracked files are not included).git commit --amend: Rewrite the last commit's message, or fold new staged changes into it. Never amend pushed commits.git commit --amend --no-edit: Add forgotten changes to the last commit without touching its message.git commit --fixup=<commit>: Create a fixup commit that autosquashes into another commit during rebase: tidy PR history.git commit --squash=<commit>: Create a squash commit to merge into another during rebase --autosquash.git diff: Show unstaged changes: what would change if you committed right now.git diff --staged: Show staged changes: exactly what the next commit will contain.git diff <file>: Show changes to a single file only.git diff HEAD: Show all changes: staged and unstaged: against the last commit.git diff --stat: Summarize changes with per-file line counts instead of full diffs.git diff main...feature: Compare your feature branch against the point it diverged from main: ignores main's newer commits.Branching & Merging
git branch: List local branches; the * marks your current branch.git branch -a: List all branches including remote-tracking branches.git branch -vv: Show which remote each branch tracks and how far ahead/behind it is.git branch <name>: Create a new branch at your current commit (does not switch to it).git switch -c <name>: Create a branch and switch to it in one move: the modern replacement for checkout -b.git switch <name>: Switch to an existing branch or remote-tracking branch.git switch -: Switch back to the branch you were on before: like cd -.git checkout <file>: Discard unstaged changes to a file, restoring it from the index.git branch -d <name>: Delete a fully merged local branch. Use -D to force-delete unmerged work.git merge <branch>: Merge another branch into your current branch, creating a merge commit.git merge --no-ff <branch>: Force a merge commit even when a fast-forward is possible: keeps feature boundaries visible.git merge --abort: Abort a conflicted merge and restore the pre-merge state.git rebase <branch>: Replay your commits on top of another branch for a linear history.git rebase -i HEAD~n: Interactive rebase: reword, reorder, squash, and drop commits in the last n.git rebase -i --autosquash HEAD~n: Automatically fold fixup! and squash! commits into their targets during interactive rebase.git rebase --continue: Continue a rebase after resolving conflicts and staging the fixes.git rebase --abort: Cancel a rebase entirely and return to the pre-rebase state.git cherry-pick <commit>: Apply a single commit from another branch onto your current one: handy for hotfixes.git cherry-pick -n <commit>: Apply a commit without committing: stage several cherry-picks for one commit.git merge --squash <branch>: Merge a branch as a single squashed change staged for one commit.Inspecting & Comparing
git log: Show commit history with full details.git log --oneline: One line per commit: hash plus subject. The default way to read history.git log --oneline --graph --all: Visual branch graph across every branch: see how history actually forked and merged.git log --oneline -n 10: Show only the last 10 commits.git log --author="jane" --oneline: Filter history by author: count your contributions or audit a teammate.git log --since="2 weeks ago" --oneline: Show commits since a date: your weekly review.git log --grep="fix:" --oneline: Search commit messages for a pattern: find every fix commit.git log -p <file>: Show the full patch history of a single file: find when a line changed.git log -S "string" --oneline: Pickaxe search: find commits that added or removed a specific string (the infamous "where did this line come from").git log -G "regex" --oneline: Find commits whose diff matches a regex: more flexible than -S.git blame <file>: Show who changed each line and in which commit: the code archaeology tool.git show <commit>: Show a commit: its metadata and full diff.git show HEAD: Show the latest commit on your branch.git show HEAD~1:path/to/file: Show a file's contents at a past commit without checking it out.git reflog: Show every HEAD movement: your safety net to recover "lost" commits after resets.git diff HEAD~1 HEAD: Compare the last commit against its parent.git shortlog -sn: Summarize commits per author, sorted: your contribution report.git count-objects -vH: Check repository size and object counts: when your .git is bloating.git rev-parse HEAD: Print the full hash of the current commit: useful in scripts and CI.git describe --tags: Describe the nearest tag to HEAD, e.g. v2.0.0-3-gabc1234: auto version labels.Undoing Changes
git restore <file>: Discard unstaged changes in a file: restore it from the index.git restore --staged <file>: Unstage a file: keep changes in the working tree.git restore --source=HEAD~1 <file>: Restore a file from a specific commit, discarding newer changes.git reset --soft HEAD~1: Undo the last commit but keep changes staged: fix a commit message or add more to it.git reset HEAD~1: Undo the last commit and unstage changes (mixed reset: working tree keeps edits).git reset --hard HEAD~1: Undo the last commit AND discard its changes entirely. Dangerous: never on pushed history.git reset --hard <commit>: Move the branch pointer and working tree to any commit: nuke everything after it.git revert <commit>: Create a new commit that undoes another commit: the safe way to undo pushed history.git revert -n <commit>: Revert without committing: combine multiple reverts or adjust first.git clean -fd: Delete untracked files and directories: clean up build artifacts or stray files.git clean -fdX: Delete only ignored files (build output, caches) while keeping untracked source.git update-ref -d HEAD: Delete the branch pointer entirely: start committing fresh in an empty repo.git bisect start && git bisect bad && git bisect good <commit>: Binary search history for the commit that introduced a bug.git bisect run <script>: Automate bisecting: a script that exits 0 for good and nonzero for bad finds the culprit.git bisect reset: Leave bisect mode and return to the original commit.Remote Collaboration
git remote -v: List remotes with fetch and push URLs.git remote add origin <url>: Add a remote: typically your GitHub/GitLab repo.git remote rename <old> <new>: Rename a remote, updating all tracking references.git remote set-url origin <url>: Change a remote URL: e.g. when switching from HTTPS to SSH or moving a repo.git remote remove <name>: Delete a remote and its tracking branches.git fetch origin: Download remote commits and branches without merging them.git fetch --prune origin: Fetch and delete local refs for branches deleted on the remote.git pull: Fetch and merge remote changes into your current branch.git pull --rebase: Fetch and rebase local commits onto the remote: cleaner linear history.git push: Push committed changes to the remote tracking branch.git push -u origin <branch>: Push a new branch and set upstream tracking: after this, plain git push works.git push --force-with-lease: Force-push only if nobody else pushed since your last fetch: the safe force.git push origin --delete <branch>: Delete a branch on the remote.git push --tags: Push all local tags to the remote: releases and version markers.git push --all origin: Push every local branch to origin at once: sync after a fresh clone.git ls-remote origin: List refs on a remote without cloning: check if a tag or branch exists.git submodule add <url> <path>: Pin an external repo inside your repo at a fixed commit.git submodule update --init --recursive: Initialize and fetch all nested submodules after cloning or switching branches.git worktree add ../hotfix main: Check out another branch in a separate directory: work on two branches without stashing.git worktree list: List all linked worktrees.git request-pull origin main https://github.com/user/repo: Generate a summary of changes to email to a maintainer when submitting patches.Stashing
git stash: Save all uncommitted changes and clean the working tree: switch branches freely.git stash push -m "message": Stash with a label so you can identify it later.git stash push <file>: Stash only specific files: keep unrelated work in place.git stash --keep-index: Stash working changes but keep staged changes: commit part of your work first.git stash list: List all stashes with their labels and branch.git stash apply: Reapply the latest stash but keep it in the list: apply to multiple branches.git stash pop: Reapply the latest stash and drop it from the list: normal workflow.git stash show -p stash@{1}: Preview a specific stash's diff before applying it.git stash drop stash@{0}: Delete a stash permanently.git stash clear: Delete every stash: clean up an untidy stash list.git stash branch <name>: Create a branch from a stash's base commit and pop the stash onto it.git stash -u: Stash untracked files too: not just tracked modifications.Tags & Releases
git tag: List all tags.git tag v1.0.0: Create a lightweight tag at the current commit.git tag -a v1.0.0 -m "Release v1.0.0": Create an annotated tag with a message: recommended for releases.git tag -a v1.0.0 <commit>: Tag a past commit: release a hotfix on an old version.git tag -d v1.0.0: Delete a local tag.git push origin --delete v1.0.0: Delete a tag on the remote.git checkout v1.0.0: Detach HEAD at a tag: inspect a release's exact code.git show v1.0.0: Show the tagged commit and its diff.git log v1.0.0..v2.0.0 --oneline: List all commits between two releases: write your changelog.git tag --contains <commit>: Find which releases contain a specific commit.Advanced History
git gc: Optimize the repository by compressing loose objects and pruning unreachable ones.git gc --aggressive --prune=now: Full housekeeping: do this when your .git folder is huge.git fsck --lost-found: Find dangling commits and objects: recover work after a botched reset.git filter-branch --force --index-filter "git rm --cached --ignore-unmatch .env" --prune-empty -- --all: Remove a file (like .env with secrets) from all of history: last resort, use filter-repo if available.git replace <old> <new>: Temporarily substitute one commit for another: graft histories without rewriting.git archive --format=zip -o release.zip HEAD: Export the current commit as a zip without the .git folder.git apply <patchfile>: Apply a diff patch file to the working tree.git format-patch -1 HEAD: Generate a patch file for the last commit: email or share it without pushing.git subtree add --prefix=lib <url> <branch>: Add a repository as a subtree: an alternative to submodules that inlines the code.git subtree pull --prefix=lib <url> <branch>: Pull upstream changes into a subtree.Frequently asked questions
How do I undo the last commit?
Use git reset --soft HEAD~1 to undo the commit but keep your changes staged, git reset --mixed HEAD~1 (default) to unstage them, or git reset --hard HEAD~1 to discard everything. Never hard-reset commits that are already pushed.
What is the difference between git merge and git rebase?
Merge creates a new commit that combines two branch histories, preserving the original timeline. Rebase rewrites your branch on top of the target branch for a linear history. Use rebase for clean local history and merge for shared branches.
How do I unstage a file?
Run git restore --staged <file> (Git 2.23+) or git reset HEAD <file>. Your working directory changes are kept: only the staging area is updated.
How do I discard local changes to a file?
Run git restore <file> to revert a tracked file to the last commit. Use git stash to save changes temporarily instead of losing them, and git clean -fd to remove untracked files.