← Back to all cheatsheets
Development
Git Cheat Sheet
Table of Contents
- Configuration
- Repository Setup
- Basic Workflow
- Staging and Committing
- Branching
- Merging
- Rebasing
- Remote Repositories
- Fetching and Pulling
- Pushing
- Viewing History
- Diff and Comparison
- Stashing
- Tagging
- Undoing Changes
- Cherry-picking
- Submodules
- Worktrees
- Searching
- Aliases
- Useful One-Liners
- Common Workflows
- Tips
Configuration
User Setup
# Set global username and email
git config --global user.name "Your Name"
git config --global user.email "[email protected]"
# Set repository-specific user
git config user.name "Work Name"
git config user.email "[email protected]"
# View all settings
git config --list
git config --list --show-origin # Show where each setting is defined
# View specific setting
git config user.name
Editor and Tools
# Set default editor
git config --global core.editor "vim"
git config --global core.editor "code --wait" # VS Code
# Set default merge tool
git config --global merge.tool vimdiff
# Set diff tool
git config --global diff.tool meld
Common Settings
# Set default branch name for new repositories
git config --global init.defaultBranch main
# Enable colored output
git config --global color.ui auto
# Set line ending preferences
git config --global core.autocrlf input # Linux/Mac
git config --global core.autocrlf true # Windows
# Store credentials
git config --global credential.helper cache # Cache for 15 min
git config --global credential.helper store # Store permanently (plaintext)
Repository Setup
Initialize and Clone
# Create new repository
git init # Initialize in current directory
git init my-project # Create new directory and initialize
# Clone existing repository
git clone https://github.com/user/repo.git
git clone [email protected]:user/repo.git # SSH
git clone https://github.com/user/repo.git my-folder # Clone into specific folder
# Clone specific branch
git clone -b develop https://github.com/user/repo.git
# Shallow clone (faster, limited history)
git clone --depth 1 https://github.com/user/repo.git
Repository Information
# Show remote URLs
git remote -v
# Show repository root directory
git rev-parse --show-toplevel
# Show current branch
git branch --show-current
git rev-parse --abbrev-ref HEAD
Basic Workflow
# Check status
git status
git status -s # Short format
# Add changes to staging
git add file.txt
git add . # Add all changes
# Commit changes
git commit -m "Commit message"
# Push to remote
git push origin main
# Pull latest changes
git pull origin main
Staging and Committing
Adding Files
# Add specific file
git add file.txt
# Add multiple files
git add file1.txt file2.txt
# Add all changes in current directory
git add .
# Add all changes in repository
git add -A
git add --all
# Add only tracked files
git add -u
# Interactive staging
git add -p # Stage hunks interactively
git add -i # Interactive mode
Committing
# Commit with message
git commit -m "Add new feature"
# Commit with multi-line message
git commit -m "Subject line" -m "Body paragraph"
# Commit all tracked changes (skip staging)
git commit -am "Quick commit"
# Amend last commit
git commit --amend # Edit message in editor
git commit --amend -m "New message" # Replace message
git commit --amend --no-edit # Keep message, add staged changes
# Empty commit (useful for triggering CI)
git commit --allow-empty -m "Trigger build"
# Commit with specific date
git commit --date="2024-01-15 10:00:00" -m "Backdated commit"
Branching
List Branches
# List local branches
git branch
git branch -v # With last commit info
# List remote branches
git branch -r
# List all branches (local and remote)
git branch -a
# List branches containing specific commit
git branch --contains <commit>
# List merged/unmerged branches
git branch --merged
git branch --no-merged
Create and Switch
# Create new branch
git branch feature-x
# Switch to branch
git checkout feature-x
git switch feature-x # Modern syntax
# Create and switch in one command
git checkout -b feature-x
git switch -c feature-x # Modern syntax
# Create branch from specific commit
git checkout -b hotfix abc1234
# Create branch tracking remote
git checkout -b feature origin/feature
git checkout --track origin/feature # Shorthand
Rename and Delete
# Rename current branch
git branch -m new-name
# Rename specific branch
git branch -m old-name new-name
# Delete local branch
git branch -d feature-x # Safe delete (must be merged)
git branch -D feature-x # Force delete
# Delete remote branch
git push origin --delete feature-x
git push origin :feature-x # Alternative syntax
Merging
Basic Merge
# Merge branch into current branch
git merge feature-x
# Merge with commit message
git merge feature-x -m "Merge feature-x into main"
# No fast-forward merge (always create merge commit)
git merge --no-ff feature-x
# Fast-forward only (fail if not possible)
git merge --ff-only feature-x
# Squash merge (combine all commits into one)
git merge --squash feature-x
git commit -m "Add feature-x"
Handling Conflicts
# View conflict markers in files
# <<<<<<< HEAD
# Your changes
# =======
# Their changes
# >>>>>>> feature-x
# After resolving conflicts
git add resolved-file.txt
git commit # Completes the merge
# Abort merge
git merge --abort
# Use specific version during conflict
git checkout --ours file.txt # Keep current branch version
git checkout --theirs file.txt # Keep incoming branch version
Rebasing
Basic Rebase
# Rebase current branch onto main
git rebase main
# Rebase onto specific branch
git rebase origin/main
# Interactive rebase (edit/squash/reorder commits)
git rebase -i HEAD~3 # Last 3 commits
git rebase -i main # All commits since branching from main
# Continue after resolving conflicts
git rebase --continue
# Abort rebase
git rebase --abort
# Skip current commit during rebase
git rebase --skip
Interactive Rebase Commands
pick = use commit
reword = use commit, but edit commit message
edit = use commit, but stop for amending
squash = use commit, but meld into previous commit
fixup = like squash, but discard commit message
drop = remove commit
Remote Repositories
Managing Remotes
# List remotes
git remote
git remote -v # With URLs
# Add remote
git remote add origin https://github.com/user/repo.git
git remote add upstream https://github.com/original/repo.git
# Remove remote
git remote remove origin
# Rename remote
git remote rename origin upstream
# Change remote URL
git remote set-url origin https://github.com/user/new-repo.git
# Show remote details
git remote show origin
Fetching and Pulling
Fetch
# Fetch from default remote
git fetch
# Fetch from specific remote
git fetch origin
# Fetch specific branch
git fetch origin main
# Fetch all remotes
git fetch --all
# Fetch and prune deleted remote branches
git fetch --prune
git fetch -p # Shorthand
Pull
# Pull (fetch + merge)
git pull
git pull origin main
# Pull with rebase instead of merge
git pull --rebase
git pull -r # Shorthand
# Set pull to always rebase
git config --global pull.rebase true
# Pull specific branch
git pull origin feature-x
Pushing
# Push current branch
git push
# Push to specific remote and branch
git push origin main
# Push and set upstream
git push -u origin feature-x
git push --set-upstream origin feature-x
# Push all branches
git push --all
# Push tags
git push --tags
git push origin v1.0.0 # Push specific tag
# Force push (use with caution!)
git push --force
git push -f # Shorthand
# Force push with lease (safer - fails if remote has new commits)
git push --force-with-lease
# Delete remote branch
git push origin --delete feature-x
Viewing History
Git Log
# Basic log
git log
git log --oneline # Compact view
git log --oneline -10 # Last 10 commits
# Graph view
git log --graph
git log --graph --oneline --all # Full branch graph
# With file changes
git log --stat # Files changed
git log -p # Full diff
# Filter by author
git log --author="John"
# Filter by date
git log --since="2024-01-01"
git log --after="2024-01-01"
git log --until="2024-06-01"
git log --since="2 weeks ago"
# Filter by message
git log --grep="bug fix"
# Filter by file
git log -- path/to/file.txt
git log -p -- path/to/file.txt # With diffs
# Custom format
git log --pretty=format:"%h %an %s"
git log --pretty=format:"%h - %an, %ar : %s"
Other History Commands
# Show specific commit
git show abc1234
git show HEAD~2 # 2 commits ago
# Who changed each line
git blame file.txt
git blame -L 10,20 file.txt # Lines 10-20
# Reference log (all HEAD movements)
git reflog
git reflog show feature-x # For specific branch
Diff and Comparison
# Working directory vs staging area
git diff
# Staging area vs last commit
git diff --staged
git diff --cached # Same as --staged
# Working directory vs last commit
git diff HEAD
# Between commits
git diff abc1234 def5678
git diff HEAD~3 HEAD # Last 3 commits
# Between branches
git diff main feature-x
git diff main...feature-x # Changes since branches diverged
# Specific file
git diff -- file.txt
git diff main feature-x -- file.txt
# Show only file names
git diff --name-only
git diff --name-status # With change type (A/M/D)
# Word diff
git diff --word-diff
# Stat summary
git diff --stat
Stashing
# Save changes to stash
git stash
git stash push -m "Work in progress" # With message
# List stashes
git stash list
# Apply most recent stash (keep in stash)
git stash apply
# Apply and remove from stash
git stash pop
# Apply specific stash
git stash apply stash@{2}
git stash pop stash@{2}
# Show stash contents
git stash show # Summary
git stash show -p # Full diff
git stash show stash@{1} -p
# Stash including untracked files
git stash -u
git stash --include-untracked
# Stash only staged changes
git stash --staged
# Create branch from stash
git stash branch feature-x stash@{0}
# Drop stash
git stash drop stash@{0}
# Clear all stashes
git stash clear
Tagging
# List tags
git tag
git tag -l "v1.*" # Filter by pattern
# Create lightweight tag
git tag v1.0.0
# Create annotated tag (recommended)
git tag -a v1.0.0 -m "Release version 1.0.0"
# Tag specific commit
git tag -a v1.0.0 abc1234 -m "Release version 1.0.0"
# Show tag details
git show v1.0.0
# Push tags to remote
git push origin v1.0.0 # Single tag
git push --tags # All tags
# Delete local tag
git tag -d v1.0.0
# Delete remote tag
git push origin --delete v1.0.0
git push origin :refs/tags/v1.0.0
# Checkout tag
git checkout v1.0.0 # Detached HEAD
git checkout -b hotfix-v1 v1.0.0 # New branch from tag
Undoing Changes
Working Directory
# Discard changes in working directory
git restore file.txt
git checkout -- file.txt # Old syntax
# Discard all changes
git restore .
git checkout -- . # Old syntax
Staging Area
# Unstage file (keep changes)
git restore --staged file.txt
git reset HEAD file.txt # Old syntax
# Unstage all files
git restore --staged .
git reset HEAD # Old syntax
Commits
# Undo last commit (keep changes staged)
git reset --soft HEAD~1
# Undo last commit (keep changes unstaged)
git reset HEAD~1
git reset --mixed HEAD~1 # Same as above
# Undo last commit (discard changes)
git reset --hard HEAD~1
# Reset to specific commit
git reset --hard abc1234
# Create new commit that undoes previous commit
git revert abc1234
git revert HEAD # Revert last commit
git revert HEAD~3..HEAD # Revert last 3 commits
# Revert merge commit
git revert -m 1 <merge-commit>
Recovery
# Find lost commits
git reflog
# Recover deleted branch
git checkout -b recovered-branch abc1234
# Recover to previous state
git reset --hard HEAD@{5}
Cherry-picking
# Apply specific commit to current branch
git cherry-pick abc1234
# Cherry-pick without committing
git cherry-pick --no-commit abc1234
git cherry-pick -n abc1234 # Shorthand
# Cherry-pick multiple commits
git cherry-pick abc1234 def5678
# Cherry-pick range
git cherry-pick abc1234..def5678 # Excludes abc1234
git cherry-pick abc1234^..def5678 # Includes abc1234
# Abort cherry-pick
git cherry-pick --abort
# Continue after resolving conflicts
git cherry-pick --continue
Submodules
# Add submodule
git submodule add https://github.com/user/repo.git path/to/submodule
# Initialize submodules after clone
git submodule init
git submodule update
git submodule update --init # Combined
# Clone with submodules
git clone --recurse-submodules https://github.com/user/repo.git
# Update all submodules
git submodule update --remote
# Remove submodule
git submodule deinit path/to/submodule
git rm path/to/submodule
rm -rf .git/modules/path/to/submodule
Worktrees
# List worktrees
git worktree list
# Add new worktree
git worktree add ../hotfix hotfix-branch
git worktree add -b new-feature ../feature # Create new branch
# Remove worktree
git worktree remove ../hotfix
# Prune stale worktrees
git worktree prune
Searching
# Search file contents
git grep "pattern"
git grep -n "pattern" # With line numbers
git grep -c "pattern" # Count matches per file
# Search in specific commit
git grep "pattern" abc1234
# Search commit messages
git log --grep="bug fix"
# Search changes (pickaxe)
git log -S "function_name" # Commits that add/remove string
git log -G "regex_pattern" # Commits matching regex in diff
# Find commit that introduced bug
git bisect start
git bisect bad # Current commit is bad
git bisect good abc1234 # Known good commit
# Test and mark each commit as good/bad
git bisect good # or: git bisect bad
git bisect reset # When done
Aliases
# Create aliases
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status
# Useful aliases
git config --global alias.unstage 'reset HEAD --'
git config --global alias.last 'log -1 HEAD'
git config --global alias.visual '!gitk'
git config --global alias.lg "log --graph --oneline --all"
git config --global alias.amend 'commit --amend --no-edit'
# Use alias
git co main # Same as: git checkout main
git lg # Pretty graph log
Useful One-Liners
# List files changed between branches
git diff --name-only main feature-x
# Count commits by author
git shortlog -sn
# Find large files in history
git rev-list --objects --all | git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' | sed -n 's/^blob //p' | sort -rnk2 | head -20
# Remove untracked files
git clean -fd # Files and directories
git clean -fdn # Dry run (preview)
# Sync fork with upstream
git fetch upstream && git merge upstream/main
# Squash last N commits
git reset --soft HEAD~N && git commit
# Find commits not yet merged to main
git log main..feature-x --oneline
# Show files in a commit
git show --name-only abc1234
# Blame with ignoring whitespace
git blame -w file.txt
# List all contributors
git log --format='%aN' | sort -u
Common Workflows
Feature Branch Workflow
# Start new feature
git checkout main
git pull origin main
git checkout -b feature/new-feature
# Work on feature
git add .
git commit -m "Add new feature"
# Keep up to date with main
git fetch origin
git rebase origin/main
# Push and create PR
git push -u origin feature/new-feature
Hotfix Workflow
# Create hotfix branch from production tag
git checkout -b hotfix/critical-fix v1.0.0
# Make fix
git add .
git commit -m "Fix critical bug"
# Merge to main and tag
git checkout main
git merge --no-ff hotfix/critical-fix
git tag -a v1.0.1 -m "Hotfix release"
git push origin main --tags
# Merge to develop
git checkout develop
git merge --no-ff hotfix/critical-fix
git push origin develop
# Delete hotfix branch
git branch -d hotfix/critical-fix
Sync Fork with Upstream
# Add upstream remote (one time)
git remote add upstream https://github.com/original/repo.git
# Sync
git fetch upstream
git checkout main
git merge upstream/main
git push origin main
Tips
Common .gitignore Patterns
# Dependencies
node_modules/
vendor/
__pycache__/
# Build outputs
dist/
build/
*.o
*.exe
# IDE/Editor
.idea/
.vscode/
*.swp
*.swo
# Environment
.env
.env.local
*.log
# OS
.DS_Store
Thumbs.db
Useful Git Configurations
# Prune on fetch automatically
git config --global fetch.prune true
# Push current branch by default
git config --global push.default current
# Auto-setup remote tracking
git config --global push.autoSetupRemote true
# Better diff algorithm
git config --global diff.algorithm histogram
# Reuse recorded resolution
git config --global rerere.enabled true
Performance Tips
# Enable filesystem cache (Windows)
git config --global core.fscache true
# Enable parallel index operations
git config --global index.threads true
# Use sparse checkout for large repos
git sparse-checkout init
git sparse-checkout set path/to/dir