A comprehensive reference organized by workflow. Covers syntax, common flags, and one-line descriptions.


Setup & Configuration

CommandDescription
git initInitialize a new Git repository in the current directory
git init --bareInitialize a bare repository (no working directory)
git clone <url>Clone a remote repository
git clone --depth <n> <url>Shallow clone with only the last N commits
git clone --filter=blob:none <url>Partial clone — download blobs on demand
git clone --recurse-submodules <url>Clone including all submodules
git config --global user.name "<name>"Set your name for all repositories
git config --global user.email "<email>"Set your email for all repositories
git config --global core.editor "<editor>"Set your default editor (vim, nano, code --wait)
git config --global init.defaultBranch mainSet default branch name for new repos
git config --list --show-originShow all config values and where they're set
git config --global alias.<name> "<cmd>"Create a Git alias

Basic Workflow

CommandDescription
git statusShow working tree status (modified, staged, untracked)
git add <file>Stage a specific file
git add .Stage all changes in current directory
git add -pStage changes interactively, hunk by hunk
git add -p <file>Interactive staging for a specific file
git commit -m "<msg>"Commit staged changes with a message
git commit -am "<msg>"Stage tracked files and commit in one step
git commit --amendModify the most recent commit (message and/or content)
git commit --amend --no-editAmend last commit without changing the message
git commit --allow-empty -m "<msg>"Create a commit with no file changes

Viewing Changes

CommandDescription
git diffShow unstaged changes (working dir vs index)
git diff --stagedShow staged changes (index vs last commit)
git diff HEADShow all changes (working dir vs last commit)
git diff <a>..<b>Show diff between two commits/branches
git diff <a>...<b>Show changes on b since it diverged from a
git diff --statShow a summary of changed files and line counts
git diff --name-onlyShow only the names of changed files
git diff --name-statusShow names and change type (A/M/D/R)
git diff --word-diffShow word-level differences (useful for prose)
git diff --checkWarn about whitespace errors
git diff --diff-filter=MShow only modified files (A=added, D=deleted, R=renamed)

Branching

CommandDescription
git branchList local branches
git branch -aList all branches (local and remote)
git branch -vList branches with last commit info
git branch -vvList branches with tracking and ahead/behind info
git branch <name>Create a new branch (don't switch to it)
git branch -d <name>Delete a merged branch
git branch -D <name>Force-delete an unmerged branch
git branch -m <old> <new>Rename a branch
git branch --mergedList branches merged into current branch
git branch --no-mergedList branches not yet merged
git switch <branch>Switch to a branch (safe — won't detach HEAD)
git switch -c <branch>Create and switch to a new branch
git switch --detach <ref>Switch to a commit in detached HEAD (explicit)
git checkout <branch>Switch to a branch (legacy — can detach HEAD)
git checkout -b <branch>Create and switch to a new branch (legacy)

Merging

CommandDescription
git merge <branch>Merge a branch into the current branch
git merge --no-ff <branch>Merge with a merge commit (no fast-forward)
git merge --squash <branch>Squash all commits into one staged change
git merge --abortAbort a merge in progress (return to pre-merge state)
git merge --continueContinue a merge after resolving conflicts
git mergetoolLaunch a visual merge conflict tool

Rebasing

CommandDescription
git rebase <branch>Rebase current branch onto another branch
git rebase -i <ref>Interactive rebase — reorder, squash, edit commits
git rebase -i HEAD~<n>Interactive rebase for the last N commits
git rebase --onto <new> <old> <branch>Transplant commits from one base to another
git rebase --abortAbort a rebase in progress
git rebase --continueContinue after resolving rebase conflicts
git rebase --skipSkip the current conflicting commit
git rebase --autosquashAuto-apply fixup!/squash! commit prefixes
git rebase --autostashStash changes before rebase, apply after

Interactive rebase commands: pick, reword, edit, squash, fixup, drop, exec


Undoing Changes

CommandDescription
git restore <file>Discard working directory changes in a file
git restore --staged <file>Unstage a file (keep working dir changes)
git restore --source=<ref> <file>Restore a file from a specific commit
git reset --soft HEAD~1Undo last commit, keep changes staged
git reset --mixed HEAD~1Undo last commit, keep changes unstaged (default)
git reset --hard HEAD~1Undo last commit, discard all changes
git reset --hard ORIG_HEADUndo the last merge/rebase/reset operation
git revert <commit>Create a new commit that undoes a commit
git revert -m 1 <merge>Revert a merge commit (keep parent 1)
git revert --no-commit <range>Revert multiple commits without auto-committing
git clean -nDry run — show untracked files that would be removed
git clean -fRemove untracked files
git clean -fdRemove untracked files and directories
git clean -fdxRemove untracked, directories, and ignored files
git clean -fdXRemove only ignored files and directories

Stashing

CommandDescription
git stashStash tracked modified and staged files
git stash -uStash including untracked files
git stash -m "<msg>"Stash with a descriptive message
git stash listList all stashes
git stash showShow the latest stash diff summary
git stash show -pShow the latest stash full diff
git stash popApply latest stash and remove it from the list
git stash applyApply latest stash (keep it in the list)
git stash apply stash@{n}Apply a specific stash
git stash drop stash@{n}Delete a specific stash
git stash clearDelete all stashes
git stash branch <name>Create a branch from a stash

Remotes

CommandDescription
git remote -vList remotes with fetch/push URLs
git remote add <name> <url>Add a new remote
git remote remove <name>Remove a remote
git remote rename <old> <new>Rename a remote
git remote set-url <name> <url>Change a remote's URL
git remote show <name>Show detailed info about a remote
git fetch <remote>Download objects and refs from a remote
git fetch --allFetch from all remotes
git fetch --pruneFetch and remove stale remote-tracking refs
git pullFetch and merge from the tracking remote
git pull --rebaseFetch and rebase instead of merge
git push <remote> <branch>Push a branch to a remote
git push -u <remote> <branch>Push and set upstream tracking
git push --force-with-leaseSafe force push (rejects if remote changed)
git push --follow-tagsPush commits and annotated tags
git push origin --delete <branch>Delete a remote branch
git branch --set-upstream-to=<remote>/<branch>Set tracking for current branch

History & Log

CommandDescription
git logShow commit history
git log --onelineCompact one-line-per-commit log
git log --oneline --graph --allVisual graph of all branches
git log --oneline --graph --decorateGraph with branch/tag labels
git log -n <N>Show only the last N commits
git log --statShow changed files per commit
git log -pShow full diffs per commit
git log --author="<name>"Filter by author
git log --since="2 weeks ago"Filter by date (also: --after, --until, --before)
git log --grep="<pattern>"Filter by commit message
git log -S "<string>"Pickaxe — find commits that add/remove a string
git log -G "<regex>"Find commits where a regex match changed
git log -- <path>Show commits that touched a specific file/directory
git log --follow -- <file>Follow file history through renames
git log -L <start>,<end>:<file>Show history of a line range in a file
git log --mergesShow only merge commits
git log --no-mergesExclude merge commits
git log --first-parentFollow only the first parent (main line)
git log --left-right <a>...<b>Show which commits are on which side
git log --pretty=format:"<fmt>"Custom format (see format placeholders below)
git shortlog -snContributor commit counts, sorted
git shortlog -sn --no-mergesCommit counts excluding merges

Format Placeholders

PlaceholderMeaning
%H / %hFull / abbreviated commit hash
%an / %aeAuthor name / email
%cn / %ceCommitter name / email
%sSubject (first line of commit message)
%bBody of commit message
%ar / %crAuthor / committer relative date
%ad / %cdAuthor / committer date
%d / %DRef names (decorated) / without wrapping
%Cred %Cgreen %Cblue %CresetColor formatting

Investigation & Debugging

CommandDescription
git blame <file>Show who last modified each line
git blame -w <file>Blame ignoring whitespace changes
git blame -C <file>Detect lines moved/copied from other files
git blame --ignore-revs-file .git-blame-ignore-revsSkip formatting commits in blame
git bisect startStart a binary search for a bug
git bisect badMark current commit as containing the bug
git bisect good <ref>Mark a known-good commit
git bisect run <script>Automate bisect with a test script
git bisect resetEnd bisect and return to original branch
git grep "<pattern>"Search file contents in current commit
git grep -n "<pattern>"Search with line numbers
git grep -p "<pattern>"Search with function/scope context
git grep -c "<pattern>"Count matches per file
git grep "<pattern>" <ref>Search in a specific commit
git show <ref>Show a commit's details and diff
git show <ref>:<file>Show a file at a specific commit
git show --stat <ref>Show commit with file change summary

Cherry-Pick

CommandDescription
git cherry-pick <commit>Apply a specific commit to the current branch
git cherry-pick -n <commit>Cherry-pick without committing (stage only)
git cherry-pick -x <commit>Cherry-pick and add "(cherry picked from ...)" to message
git cherry-pick <a>..<b>Cherry-pick a range of commits (excludes a)
git cherry-pick --abortAbort a cherry-pick in progress
git cherry-pick --continueContinue after resolving conflicts

Tags

CommandDescription
git tagList all tags
git tag -l "v1.*"List tags matching a pattern
git tag <name>Create a lightweight tag
git tag -a <name> -m "<msg>"Create an annotated tag
git tag -a <name> <commit>Tag a specific commit
git tag -d <name>Delete a local tag
git push origin <tag>Push a specific tag to remote
git push --follow-tagsPush commits and annotated tags
git push --tagsPush all tags to remote
git push origin --delete <tag>Delete a remote tag

Reflog & Recovery

CommandDescription
git reflogShow history of HEAD movements
git reflog show <branch>Show reflog for a specific branch
git reflog --date=isoShow reflog with timestamps
git fsck --unreachableFind unreachable objects
git fsck --lost-foundSave dangling commits to .git/lost-found/

Worktrees

CommandDescription
git worktree add <path> <branch>Create a linked worktree for a branch
git worktree add <path> -b <new>Create a worktree with a new branch
git worktree listList all worktrees
git worktree remove <path>Remove a linked worktree
git worktree pruneClean up stale worktree references

Submodules

CommandDescription
git submodule add <url> <path>Add a submodule
git submodule update --init --recursiveInitialize and fetch all submodules
git submodule update --remoteUpdate submodules to latest remote commit
git submodule syncSync submodule URLs after .gitmodules change
git submodule deinit <path>Unregister a submodule
git submodule foreach '<cmd>'Run a command in each submodule

Subtrees

CommandDescription
git subtree add --prefix=<dir> <url> <branch> --squashAdd a subtree
git subtree pull --prefix=<dir> <url> <branch> --squashPull updates into a subtree
git subtree push --prefix=<dir> <url> <branch>Push subtree changes back upstream

Git LFS

CommandDescription
git lfs installInitialize Git LFS for the current user
git lfs track "<pattern>"Track files matching a pattern with LFS
git lfs untrack "<pattern>"Stop tracking a pattern with LFS
git lfs ls-filesList files tracked by LFS
git lfs statusShow LFS file status
git lfs pullDownload LFS file content
git lfs fetch --recentPre-fetch LFS files for recent branches
git lfs migrate import --include="<pattern>"Retroactively move files to LFS

Sparse Checkout & Partial Clone

CommandDescription
git clone --sparse <url>Clone with sparse checkout (root files only)
git clone --filter=blob:none --sparse <url>Sparse partial clone (optimal for monorepos)
git sparse-checkout set --cone <dirs>Set directories to check out
git sparse-checkout add <dir>Add a directory to sparse checkout
git sparse-checkout listList checked-out directories
git sparse-checkout disableDisable sparse checkout (get all files)

Hooks

HookWhen It Runs
pre-commitBefore commit is created (lint, format, test)
prepare-commit-msgAfter default message generated, before editor opens
commit-msgAfter message written (validate commit message format)
post-commitAfter commit is created (notifications)
pre-pushBefore push (run tests, check branch rules)
post-mergeAfter a merge (install deps, rebuild)
pre-rebaseBefore rebase starts (prevent on shared branches)
CommandDescription
git config core.hooksPath <dir>Set custom hooks directory
git commit --no-verifySkip pre-commit and commit-msg hooks
git push --no-verifySkip pre-push hook

Performance & Maintenance

CommandDescription
git gcRun garbage collection
git gc --aggressiveThorough GC with maximum compression
git maintenance startEnable background scheduled maintenance
git maintenance runRun all maintenance tasks now
git commit-graph write --reachable --changed-pathsGenerate commit-graph with Bloom filters
git count-objects -vShow object storage statistics
git config core.fsmonitor trueEnable filesystem monitor (speeds up git status)
git config core.untrackedCache trueCache untracked file state
git config rerere.enabled trueEnable reuse of recorded conflict resolutions
git rerere forget <file>Forget a recorded resolution
git repack -a -dRepack all objects into one packfile

Commit Signing

CommandDescription
git config gpg.format sshUse SSH keys for signing
git config user.signingkey <key>Set signing key (GPG ID or SSH pubkey path)
git config commit.gpgsign trueSign all commits automatically
git config tag.gpgsign trueSign all tags automatically
git commit -S -m "<msg>"Create a signed commit (one-time)
git tag -s <name> -m "<msg>"Create a signed tag
git log --show-signatureShow signatures in log
git verify-commit <commit>Verify a commit's signature
git verify-tag <tag>Verify a tag's signature

Git Notes

CommandDescription
git notes add -m "<msg>" <commit>Add a note to a commit
git notes append -m "<msg>" <commit>Append to an existing note
git notes edit <commit>Edit a note in your editor
git notes remove <commit>Remove a note
git notes --ref=<ns> add -m "<msg>"Add a note in a namespace
git log --show-notesShow notes in log output
git log --show-notes="*"Show notes from all namespaces

Useful Inspection Commands

CommandDescription
git rev-parse HEADShow the full SHA of HEAD
git rev-parse --abbrev-ref HEADShow current branch name
git cat-file -t <hash>Show object type (blob/tree/commit/tag)
git cat-file -p <hash>Pretty-print object contents
git ls-filesList all tracked files
git ls-tree HEADList files in the current commit's tree
git hash-object <file>Compute the SHA-1 hash of a file
git check-mailmap "<name> <email>"Test .mailmap resolution

Graph Traversal Syntax

SyntaxMeaning
HEAD~1 or HEAD~First parent (one generation back)
HEAD~3Three generations back (great-grandparent)
HEAD^1 or HEAD^First parent of a merge
HEAD^2Second parent of a merge (the merged branch)
HEAD~2^2Second parent of the grandparent
@Shorthand for HEAD
@{-1}The branch you were on before the last git switch
main@{upstream} or main@{u}Upstream tracking branch for main

Range Notation

SyntaxIn git logIn git diff
A..BCommits reachable from B but not ADiff between A and B
A...BCommits reachable from either but not bothDiff of B since it diverged from A

Common .gitignore Patterns

# Build output
build/
dist/
*.o
*.class
 
# Dependencies
node_modules/
vendor/
.venv/
 
# IDE files
.idea/
.vscode/
*.swp
*.swo
 
# OS files
.DS_Store
Thumbs.db
 
# Environment/secrets
.env
.env.local
*.pem
*.key
 
# Logs
*.log
logs/
 
# Coverage/testing
coverage/
.nyc_output/

Quick Reference: Everyday Commands

# Morning routine
git fetch --prune
git status
 
# Feature development
git switch -c feature/my-feature
git add -p                          # stage interactively
git commit -m "feat: add feature"
git push -u origin feature/my-feature
 
# Stay up to date
git fetch origin
git rebase origin/main
 
# After code review
git push --force-with-lease
 
# Clean up after merge
git switch main
git pull
git branch -d feature/my-feature