Git Cheatsheet

A User-friendly guide to Git version control. Learn essential commands, branching strategies, and advanced features.

Basic Commands

Repository Setup

Initialize and clone repositories.

// Initialize a new repository
git init

// Clone existing repository
git clone <repository-url>

// Clone specific branch
git clone -b <branch-name> <repository-url>

// Clone with depth limit (shallow clone)
git clone --depth=1 <repository-url>

// Show remote repository URL
git remote -v

// Add remote repository
git remote add origin <repository-url>

// Change remote URL
git remote set-url origin <new-url>

Basic Operations

Common daily Git commands.

// Check status
git status

// Stage changes
git add <file-name>
git add .                  # Stage all changes
git add -p                 # Stage changes interactively

// Commit changes
git commit -m "message"
git commit -am "message"   # Stage tracked files and commit

// Push changes
git push origin <branch>
git push -u origin <branch>  # Set upstream branch

// Pull changes
git pull origin <branch>
git pull --rebase origin <branch>  # Pull with rebase

// Fetch changes
git fetch origin
git fetch --all           # Fetch all remotes

Branch Management

Branch Operations

Working with branches.

// List branches
git branch                 # Local branches
git branch -r             # Remote branches
git branch -a             # All branches

// Create branch
git branch <branch-name>
git checkout -b <branch-name>  # Create and switch
git switch -c <branch-name>    # Create and switch (new syntax)

// Switch branches
git checkout <branch-name>
git switch <branch-name>       # New syntax

// Delete branch
git branch -d <branch-name>    # Safe delete
git branch -D <branch-name>    # Force delete
git push origin --delete <branch-name>  # Delete remote

// Rename branch
git branch -m <new-name>       # Rename current branch
git branch -m <old> <new>      # Rename specific branch

Merging and Rebasing

Combining branches and managing history.

// Merge branch
git merge <branch-name>
git merge --no-ff <branch>     # Create merge commit
git merge --abort             # Abort merge

// Rebase
git rebase <branch>
git rebase -i HEAD~3          # Interactive rebase
git rebase --abort            # Abort rebase

// Cherry-pick
git cherry-pick <commit-hash>
git cherry-pick <hash1>..<hash2>  # Range of commits

// Squash commits
git reset --soft HEAD~3       # Soft reset to squash
git commit -m "squashed message"   # New commit

History and Diffs

Viewing History

Inspect repository history.

// View commit history
git log
git log --oneline           # Compact view
git log --graph --oneline   # Graph view
git log -p                  # With diffs
git log --author="name"     # Filter by author
git log --since="2 weeks"   # Filter by date

// View changes
git diff                    # Unstaged changes
git diff --staged          # Staged changes
git diff <commit1> <commit2>  # Between commits
git diff <branch1>..<branch2> # Between branches

// Show commit details
git show <commit-hash>
git show HEAD              # Latest commit
git show HEAD~1            # Previous commit

// Blame
git blame <file>           # Line by line history
git blame -L 10,20 <file>  # Specific lines

Search and Filter

Find specific changes and commits.

// Search commits
git log --grep="keyword"   # Search commit messages
git log -S"code"           # Search code changes
git log -G"regex"          # Search with regex

// Find lost commits
git reflog                 # Reference log
git fsck --lost-found     # Find dangling commits

// Filter history
git log --after="2023-01-01"
git log --before="2023-12-31"
git log --author="name"
git log --merges          # Only merge commits
git log --no-merges       # Exclude merges

Undoing Changes

Reset and Restore

Undo changes at different stages.

// Unstage changes
git restore --staged <file>    # New syntax
git reset HEAD <file>          # Old syntax

// Discard changes
git restore <file>             # New syntax
git checkout -- <file>         # Old syntax

// Reset commits
git reset --soft HEAD~1        # Keep changes staged
git reset --mixed HEAD~1       # Keep changes unstaged
git reset --hard HEAD~1        # Discard changes

// Revert commits
git revert <commit-hash>
git revert HEAD               # Revert last commit
git revert -n <commit>        # Revert without commit

// Clean working directory
git clean -n                  # Dry run
git clean -f                  # Force clean
git clean -fd                 # Include directories
git clean -fx                 # Include ignored files

Stashing

Temporarily store changes.

// Basic stash operations
git stash                     # Stash changes
git stash save "message"      # Stash with message
git stash -u                  # Include untracked
git stash -a                  # Include ignored

// Apply stash
git stash pop                 # Apply and remove
git stash apply              # Apply and keep
git stash apply stash@{2}    # Apply specific stash

// Manage stashes
git stash list               # List stashes
git stash show              # Show stash changes
git stash drop              # Remove last stash
git stash clear             # Remove all stashes

// Stash specific files
git stash push -m "msg" <file>
git stash push -p            # Interactive stash

Advanced Features

Submodules

Working with submodules.

// Add submodule
git submodule add <url> <path>
git submodule init
git submodule update

// Update submodules
git submodule update --remote
git submodule foreach git pull

// Remove submodule
git submodule deinit <path>
git rm <path>
git commit -m "Remove submodule"

Worktrees

Manage multiple working trees.

// Create worktree
git worktree add <path> <branch>
git worktree add -b <new-branch> <path>

// List worktrees
git worktree list

// Remove worktree
git worktree remove <path>
git worktree prune           # Clean up

// Move worktree
git worktree move <path> <new-path>

Configuration

Git Config

Configure Git settings.

// User configuration
git config --global user.name "Name"
git config --global user.email "email"

// Aliases
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.st status

// Core settings
git config --global core.editor "code --wait"
git config --global core.autocrlf true
git config --global pull.rebase true

// List configuration
git config --list
git config --global --list

Ignore Files

Configure Git ignore patterns.

// .gitignore patterns
# Ignore file
file.txt

# Ignore directory
node_modules/

# Ignore by pattern
*.log
build/
dist/

# Negation
!important.log

// Global ignore
git config --global core.excludesfile ~/.gitignore_global

Git Workflows

GitFlow

Popular branching strategy for managing releases.

// Main branches
main (or master)     # Production code
develop              # Development code

// Supporting branches
feature/*            # New features
release/*           # Release preparation
hotfix/*            # Production fixes

// Feature workflow
git checkout develop
git checkout -b feature/new-feature
git push -u origin feature/new-feature
// After code review
git checkout develop
git merge feature/new-feature

// Release workflow
git checkout develop
git checkout -b release/1.0.0
// Fix any release issues
git checkout main
git merge release/1.0.0
git checkout develop
git merge release/1.0.0

Trunk-Based Development

Alternative workflow focusing on small, frequent changes.

// Main branch only
main                 # Single source of truth

// Feature flags
git checkout -b feature/quick-change
// Implement with feature flag
git checkout main
git merge feature/quick-change

// Short-lived feature branches
// Should live < 24 hours
git checkout -b small-feature
git commit -am "Add feature"
git push
// Create PR and merge quickly

Advanced Git Operations

Bisect

Binary search through history to find bugs.

// Start bisect
git bisect start
git bisect bad                # Current commit is bad
git bisect good <commit-hash> # Last known good commit

// Automated bisect
git bisect run npm test      # Run test command

// After finding bad commit
git bisect reset            # End bisect session

// Bisect with script
git bisect start HEAD <good-commit>
git bisect run ./test.sh

Hooks

Automate actions before/after Git events.

// Common hook locations
.git/hooks/pre-commit
.git/hooks/pre-push
.git/hooks/commit-msg

// Pre-commit hook example
#!/bin/sh
npm run lint
npm run test

// Commit message hook
#!/bin/sh
commit_msg=$(cat "$1")
if ! echo "$commit_msg" | grep -qE "^(feat|fix|docs|style|refactor|test|chore):"; then
    echo "Error: Invalid commit message format"
    exit 1
fi

// Push hook
#!/bin/sh
npm run build
npm run test:e2e

Git Internals

Objects and Refs

Understanding Git's internal structure.

// Git objects
blob                # File content
tree                # Directory structure
commit             # Snapshot of changes
tag                # Named reference

// View object content
git cat-file -p <hash>    # Pretty print object
git cat-file -t <hash>    # Show object type

// List all objects
git rev-list --objects --all

// View packed objects
git verify-pack -v .git/objects/pack/*.idx

// Reference management
git update-ref refs/heads/main <commit-hash>
git symbolic-ref HEAD refs/heads/main

Reflogs

Track reference changes history.

// View reflog
git reflog                # Show HEAD reflog
git reflog show <branch>  # Show branch reflog

// Restore from reflog
git reset --hard HEAD@{1}  # Go back one step
git checkout HEAD@{2}      # Check out older state

// Expire reflog entries
git reflog expire --expire=30.days.ago
git reflog expire --expire-unreachable=now

// Recover deleted branch
git checkout -b recover-branch HEAD@{1}

Collaboration Tools

Patch Management

Create and apply patches between repositories.

// Create patch
git format-patch main..feature    # Create patch files
git format-patch -1 <commit>      # Single commit patch
git format-patch -n <commit>      # Last n commits

// Apply patch
git apply --check patch-file.patch  # Test patch
git am < patch-file.patch           # Apply patch
git am --abort                      # Abort patch

// Create patch series
git format-patch -M main
git send-email *.patch

Remote Management

Advanced remote repository operations.

// Multiple remotes
git remote add upstream <url>
git fetch --all --prune

// Track remote branches
git branch -u origin/main
git push -u origin feature

// Remote pruning
git remote prune origin --dry-run
git remote prune origin

// Mirror repository
git clone --mirror <url>
git push --mirror <new-url>

// Shallow clone with history
git clone --depth=1 <url>
git fetch --unshallow

Troubleshooting

Debugging

Tools for debugging Git issues.

// Debug with environment variables
GIT_TRACE=1                    # General traces
GIT_TRACE_PERFORMANCE=1        # Performance data
GIT_TRACE_PACK_ACCESS=1       # Pack access
GIT_TRACE_PACKET=1            # Protocol packets
GIT_TRACE_SETUP=1             # Setup info

// Find merge conflicts
git diff --check
git diff --name-only --diff-filter=U

// Fix corrupted repository
git fsck --full
git prune
git repack -a -d
git gc --aggressive

Recovery Operations

Recover from common Git mistakes.

// Recover lost commits
git fsck --lost-found
git show <dangling-commit>

// Recover from bad merge
git merge --abort
git reset --merge ORIG_HEAD

// Recover deleted branch
git reflog
git checkout -b recovery <commit-hash>

// Fix detached HEAD
git log --oneline   # Find commit hash
git checkout -b new-branch
git checkout main
git merge new-branch