Git Command Reference

This is the lookup page — a command cheat sheet organized by task (initialize, stage, branch, sync, undo, recover). Scan it or use your browser’s find (Ctrl/Cmd-F) for the syntax you need. If you are learning Git, start with the Git Crash Course; for how Git works internally, see Git Version Control; for team workflows, Branching Strategies.

Two habits prevent most lost work. Before any history-rewriting command (reset --hard, rebase, commit --amend on shared work): (1) git reflog records where HEAD has been, so almost nothing is truly gone — you can usually git reset --hard HEAD@{n} back to safety; (2) when collaborating, prefer git push --force-with-lease over --force, so you never silently clobber a teammate’s pushed commits.

Repository Initialization

Creating a New Repository

git init

Initializes a new Git repository in the current directory, creating a .git subdirectory containing all repository metadata.

Cloning an Existing Repository

git clone <repository-url>
git clone <repository-url> <directory-name>

Creates a local copy of a remote repository. The second form allows specifying a custom directory name.

Configuration

User Configuration

git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"

View Configuration

git config --list
git config user.name

Basic Workflow Commands

Status and Differences

git status              # Show working tree status
git diff                # Show unstaged changes
git diff --staged       # Show staged changes
git diff HEAD           # Show all changes since last commit

Staging Changes

git add <file>          # Stage specific file
git add .               # Stage all changes in current directory
git add -A              # Stage all changes in repository
git add -p              # Interactive staging

Committing Changes

git commit -m "Commit message"       # Commit with inline message
git commit                           # Opens editor for message
git commit -am "Message"             # Stage and commit tracked files
git commit --amend                   # Modify last commit

History and Inspection

Viewing History

git log                              # Show commit history
git log --oneline                    # Compact format
git log --graph                      # ASCII graph of branches
git log --stat                       # Include file changes
git log -p                           # Show patches
git log --author="Name"              # Filter by author
git log --since="2 weeks ago"        # Time-based filtering

Examining Commits

git show                             # Show last commit
git show <commit-hash>               # Show specific commit
git show <commit-hash>:<file>        # Show file at specific commit

Branching and Merging

Branch Management

git branch                           # List local branches
git branch -a                        # List all branches
git branch <branch-name>             # Create new branch
git branch -d <branch-name>          # Delete branch (safe)
git branch -D <branch-name>          # Force delete branch

Switching Branches

git checkout <branch-name>           # Switch to branch
git checkout -b <branch-name>        # Create and switch to branch
git switch <branch-name>             # Modern alternative to checkout (Git 2.23+)
git switch -c <branch-name>          # Create and switch (modern)
git switch -                         # Switch to previous branch

Merging

git merge <branch-name>              # Merge branch into current
git merge --no-ff <branch-name>      # Force merge commit
git merge --squash <branch-name>     # Combine all branch work into one staged change
git merge --abort                    # Abort conflicted merge
Style Result Good for
Fast-forward (default when possible) No merge commit; branch pointer just advances Tidy linear history
--no-ff Always records a merge commit Preserving that a feature was a discrete unit
--squash Flattens the branch into one new commit you commit yourself A single clean commit per feature on main

Remote Operations

Remote Management

git remote                           # List remotes
git remote -v                        # Show remote URLs
git remote add <name> <url>          # Add new remote
git remote remove <name>             # Remove remote
git remote rename <old> <new>        # Rename remote

Synchronization

git fetch                            # Download remote changes
git fetch <remote>                   # Fetch from specific remote
git pull                             # Fetch and merge
git pull --rebase                    # Fetch and rebase
git push                             # Upload local changes
git push <remote> <branch>           # Push specific branch
git push -u origin <branch>          # Set upstream and push

fetch vs pull: git fetch downloads remote changes but leaves your working branch untouched — you inspect, then merge or rebase deliberately. git pull is just fetch + merge (or fetch + rebase with --rebase) in one step. When in doubt, fetch first and look before you integrate.

Undoing Changes

Working Directory

git restore <file>                   # Discard changes (Git 2.23+)
git checkout -- <file>               # Discard changes (legacy)
git clean -fd                        # Remove untracked files

Staging Area

git restore --staged <file>          # Unstage file (Git 2.23+)
git reset HEAD <file>                # Unstage file (legacy)

Commits

git reset --soft HEAD~1              # Undo commit, keep changes staged
git reset --mixed HEAD~1             # Undo commit, unstage changes (default)
git reset --hard HEAD~1              # Undo commit, discard changes
git revert <commit>                  # Create new commit undoing changes
git revert --no-commit <commit>      # Revert without committing
git revert -m 1 <merge-commit>       # Revert a merge commit

The three reset modes differ only in how far back they roll the changes — choose by what you want to keep:

Mode Moves branch Staging area Working files Use when
--soft yes kept kept Re-commit differently (e.g. squash, reword)
--mixed (default) yes reset kept Unstage and rework before committing
--hard yes reset discarded Throw the work away entirely

reset vs revert. reset rewrites history by moving the branch pointer — safe on local, unpushed commits only. To undo something already pushed and shared, use git revert, which records a new commit that cancels the old one and leaves history intact.

Stashing

git stash                            # Save changes temporarily
git stash push -m "Description"      # Stash with message
git stash list                       # List stashes
git stash apply                      # Apply most recent stash
git stash apply stash@{n}            # Apply specific stash
git stash pop                        # Apply and remove stash
git stash drop stash@{n}             # Remove specific stash
git stash clear                      # Remove all stashes

Tags

git tag                              # List tags
git tag <tag-name>                   # Create lightweight tag
git tag -a <tag-name> -m "Message"   # Create annotated tag
git tag -d <tag-name>                # Delete local tag
git push origin <tag-name>           # Push tag to remote
git push origin --tags               # Push all tags

Advanced Operations

Rebasing

git rebase <branch>                  # Rebase current branch
git rebase -i HEAD~n                 # Interactive rebase last n commits
git rebase --continue                # Continue after resolving conflicts
git rebase --abort                   # Cancel rebase

Cherry-picking

git cherry-pick <commit>             # Apply specific commit
git cherry-pick --continue           # Continue after resolving conflicts
git cherry-pick --abort              # Cancel cherry-pick

Searching

git grep <pattern>                   # Search in working directory
git log -S <string>                  # Find commits that add/remove string
git log --grep=<pattern>             # Search commit messages

Performance and Maintenance

Optimization

git gc                               # Garbage collection
git prune                            # Remove unreachable objects
git fsck                             # Check repository integrity

Large Files

git lfs track "*.psd"                # Track file type with Git LFS
git lfs ls-files                     # List LFS tracked files

Common Workflows

Feature Branch Workflow

git checkout -b feature/new-feature  # Create feature branch
# Make changes
git add .
git commit -m "Add new feature"
git push -u origin feature/new-feature
# Create pull request

Hotfix Workflow

git checkout main
git checkout -b hotfix/critical-fix
# Make fix
git add .
git commit -m "Fix critical issue"
git checkout main
git merge hotfix/critical-fix
git push

Best Practices

  • Write messages in the imperative mood (“Add”, “Fix”, “Remove”) with a concise first line under ~50 characters.
  • Keep commits atomic — one logical change each, so they can be reviewed, reverted, or cherry-picked independently.
  • Name branches descriptively with a type prefix (feature/, bugfix/, hotfix/).
  • Sync before you pushgit pull --rebase keeps history linear and avoids surprise conflicts.
  • Review before you commit with git diff --staged, and stage selectively with git add -p.
  • Prefer --force-with-lease over --force so you never clobber a teammate’s pushed work.

Advanced Features (2023-2024)

Worktrees

git worktree add <path> <branch>     # Create new worktree
git worktree list                    # List all worktrees
git worktree remove <path>           # Remove worktree
git worktree prune                   # Clean up stale worktrees

Sparse Checkout

git sparse-checkout init             # Initialize sparse checkout
git sparse-checkout set <dir1> <dir2> # Set directories to include
git sparse-checkout list             # Show current sparse patterns
git sparse-checkout disable          # Disable sparse checkout

Maintenance and Performance

git maintenance start                # Enable automatic maintenance
git maintenance run                  # Run maintenance tasks
git maintenance stop                 # Disable automatic maintenance
git commit-graph write               # Generate commit graph
git multi-pack-index write           # Optimize pack files

Advanced Diff and Merge

git diff --color-words               # Show word-level differences
git diff --word-diff                 # Alternative word diff format
git diff --name-status               # Show only file names and status
git diff --check                     # Check for whitespace errors
git merge --no-ff                    # Force merge commit
git merge --squash                   # Squash branch into single commit
git rerere                           # Reuse recorded resolution

Bundle Operations

git bundle create <file> <refs>      # Create bundle file
git bundle verify <file>             # Verify bundle
git bundle list-heads <file>         # List references in bundle
git clone <bundle-file> <dir>        # Clone from bundle

Bisect for Bug Finding

git bisect start                     # Start bisect session
git bisect bad                       # Mark current commit as bad
git bisect good <commit>             # Mark known good commit
git bisect skip                      # Skip current commit
git bisect reset                     # End bisect session
git bisect run <script>              # Automate bisect with script

Signing and Verification

git config --global user.signingkey <key-id>  # Set GPG key
git config --global commit.gpgsign true        # Auto-sign commits
git config --global tag.gpgsign true           # Auto-sign tags
git commit -S -m "Signed commit"               # Sign specific commit
git tag -s <tag-name> -m "Signed tag"          # Create signed tag
git verify-commit <commit>                      # Verify commit signature
git verify-tag <tag>                            # Verify tag signature

SSH Signing (Git 2.34+)

git config gpg.format ssh                       # Use SSH for signing
git config user.signingkey ~/.ssh/id_ed25519   # Set SSH key
git config gpg.ssh.allowedSignersFile ~/.config/git/allowed_signers

Troubleshooting

Common Issues

Detached HEAD State

git checkout <branch-name>           # Return to branch
git checkout -b <new-branch>         # Create branch from current state
git switch -c <new-branch>           # Modern way to create branch

Merge Conflicts

# Edit conflicted files manually
git add <resolved-files>
git commit                           # Complete merge
# Or use merge tool
git mergetool                        # Launch configured merge tool

Wrong Branch Commits

git cherry-pick <commit>             # Copy commit to correct branch
git reset --hard HEAD~1              # Remove from wrong branch
# Or move last n commits to new branch
git branch <new-branch>
git reset --hard HEAD~n
git checkout <new-branch>

Large File Issues (purge a big/sensitive file from all history)

# Preferred: git-filter-repo (fast, safe; install via pip/package manager)
git filter-repo --path <large-file> --invert-paths

# Legacy fallback only — git filter-branch is deprecated and error-prone
git filter-branch --tree-filter 'rm -f <large-file>' HEAD

Rewriting history changes every downstream commit hash. Coordinate with collaborators and force-push afterward; everyone else must re-clone or hard-reset.

Corrupted Repository

git fsck --full                      # Check repository integrity
git gc --prune=now                   # Clean up repository
git reflog expire --expire=now --all # Expire all reflog entries

Performance Optimization

Config Optimizations

git config core.preloadindex true    # Speed up git status
git config core.fscache true         # Enable file system cache (Windows)
git config core.untrackedCache true  # Cache untracked files
git config feature.manyFiles true    # Optimize for many files

Large Repository Handling

# Shallow clone
git clone --depth 1 <url>            # Clone only latest commit
git clone --shallow-since=<date>     # Clone from specific date
git clone --shallow-exclude=<rev>    # Exclude specific revision

# Partial clone
git clone --filter=blob:none <url>   # Clone without file contents
git clone --filter=tree:0 <url>      # Clone without trees

Integration with Development Tools

VS Code Integration

git config --global core.editor "code --wait"
git config --global diff.tool vscode
git config --global difftool.vscode.cmd 'code --wait --diff $LOCAL $REMOTE'

GitHub CLI Integration

gh repo clone <owner>/<repo>         # Clone with GitHub CLI
gh pr create                         # Create pull request
gh pr checkout <number>              # Checkout PR locally
gh issue create                      # Create issue

Pre-commit Hooks

# Install pre-commit framework
pip install pre-commit
pre-commit install                   # Install git hooks
pre-commit run --all-files          # Run on all files

Security Best Practices

Removing Sensitive Data

# Preferred: git-filter-repo (the tool Git itself now recommends)
git filter-repo --path <sensitive-file> --invert-paths

# Legacy fallback (filter-branch is deprecated):
git filter-branch --force --index-filter \
  'git rm --cached --ignore-unmatch <file>' \
  --prune-empty --tag-name-filter cat -- --all

A leaked secret in history must be treated as compromised even after removal — rotate the credential, then purge it from history.

Secret Scanning

# Use tools like git-secrets
git secrets --install
git secrets --register-aws          # Register AWS patterns
git secrets --scan                  # Scan for secrets

Additional Resources


See Also