Git - Cheat Sheet

Reference

Quick reference guide to the most essential Git commands and workflows. Perfect for developers who need fast access to Git syntax and common operations.

Setup and Configuration

# Initial setup
git config --global user.name "Your Name"
git config --global user.email "[email protected]"
git config --global init.defaultBranch main
git config --global pull.rebase true

# View configuration
git config --list
git config user.name

# Create repository
git init
git clone <url>

Basic Workflow

# Check status
git status
git status -s  # Short format

# Add files
git add file.txt
git add .        # All files
git add *.js     # Pattern matching
git add -A       # All including deletions

# Commit changes
git commit -m "Commit message"
git commit -am "Add and commit"  # Tracked files only
git commit --amend              # Modify last commit

# View history
git log
git log --oneline
git log --graph --decorate
git log -p        # Show patches
git log -5        # Last 5 commits

Branching

# List branches
git branch
git branch -a    # All branches (local + remote)
git branch -r    # Remote branches only

# Create and switch
git branch feature-name
git checkout feature-name
git checkout -b feature-name    # Create and switch
git switch -c feature-name      # Modern syntax

# Switch branches
git checkout main
git switch main                 # Modern syntax
git checkout -                  # Previous branch

# Delete branches
git branch -d feature-name      # Safe delete
git branch -D feature-name      # Force delete
git push origin --delete branch-name  # Delete remote

Merging

# Merge branch
git merge feature-branch
git merge --no-ff feature-branch    # Always create merge commit
git merge --squash feature-branch   # Squash commits

# Merge tools
git mergetool

# Abort merge
git merge --abort

Remote Repositories

# Add remote
git remote add origin <url>
git remote -v                   # View remotes

# Fetch and pull
git fetch                       # Download without merge
git fetch origin
git pull                        # Fetch + merge
git pull origin main
git pull --rebase              # Fetch + rebase

# Push
git push
git push origin main
git push -u origin main        # Set upstream
git push --force-with-lease    # Safer force push

Undoing Changes

# Unstage files
git reset HEAD file.txt
git restore --staged file.txt  # Modern syntax

# Discard changes
git checkout -- file.txt
git restore file.txt           # Modern syntax
git clean -fd                  # Remove untracked files

# 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>       # Safe undo

Stashing

# Stash changes
git stash
git stash save "Work in progress"
git stash -u                   # Include untracked files

# List and apply stashes
git stash list
git stash show stash@{0}
git stash apply                # Keep stash
git stash pop                  # Apply and remove
git stash apply stash@{2}      # Specific stash

# Drop stashes
git stash drop stash@{0}
git stash clear                # Remove all

Tagging

# Create tags
git tag v1.0                   # Lightweight tag
git tag -a v1.0 -m "Version 1.0"  # Annotated tag
git tag -a v1.0 <commit-hash>      # Tag specific commit

# List and show tags
git tag
git tag -l "v1.*"              # Pattern matching
git show v1.0

# Push tags
git push origin v1.0
git push origin --tags         # All tags

# Delete tags
git tag -d v1.0                # Local
git push origin --delete v1.0  # Remote

Viewing Differences

# Show differences
git diff                       # Working vs staged
git diff --staged              # Staged vs last commit
git diff HEAD                  # Working vs last commit
git diff branch1 branch2       # Between branches
git diff HEAD~1 HEAD           # Between commits

# Show specific commits
git show <commit-hash>
git show HEAD~2
git show --stat <commit-hash>  # Statistics only

Advanced History

# Interactive rebase
git rebase -i HEAD~3
git rebase -i main

# Cherry-pick
git cherry-pick <commit-hash>
git cherry-pick --no-commit <hash>  # Don't auto-commit

# Blame
git blame file.txt
git blame -L 10,20 file.txt    # Specific lines

# Bisect
git bisect start
git bisect bad                 # Current commit is bad
git bisect good v1.0          # v1.0 is good
git bisect reset              # End bisect

Search and Find

# Search in files
git grep "search term"
git grep -n "search term"     # Show line numbers
git grep -l "search term"     # Show file names only

# Search in history
git log --grep="bug fix"
git log -S "function_name"    # Pickaxe search
git log -p -- file.txt        # File history

# Find commits
git log --author="John Doe"
git log --since="2 weeks ago"
git log --until="2023-01-01"

File Operations

# Rename/move files
git mv old-name.txt new-name.txt

# Remove files
git rm file.txt
git rm --cached file.txt       # Remove from tracking only

# Ignore files
echo "*.log" >> .gitignore
git add .gitignore

Useful Aliases

# Set up useful aliases
git config --global alias.st status
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
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 --oneline --graph --decorate'

Branch Comparison

# Compare branches
git log main..feature          # Commits in feature not in main
git log feature..main          # Commits in main not in feature
git log main...feature         # Commits unique to each branch

# Show branch relationships
git show-branch main feature
git merge-base main feature    # Common ancestor

Recovery and Maintenance

# Reflog (recovery)
git reflog
git reflog --all
git reset --hard HEAD@{5}     # Go back to reflog entry

# Maintenance
git gc                         # Garbage collection
git fsck                       # File system check
git count-objects -v           # Repository statistics

# Find lost commits
git fsck --lost-found

Working with Patches

# Create patches
git format-patch -1 HEAD      # Last commit
git format-patch main         # All commits since main
git diff > changes.patch      # Working directory patch

# Apply patches
git apply changes.patch
git am 0001-commit.patch      # Apply mailed patch

Submodules

# Add submodule
git submodule add <url> path/to/submodule

# Initialize submodules
git submodule init
git submodule update
git submodule update --init --recursive  # One command

# Update submodules
git submodule update --remote

Advanced Configuration

# Line ending configuration
git config --global core.autocrlf true   # Windows
git config --global core.autocrlf input  # macOS/Linux

# Editor configuration
git config --global core.editor "code --wait"
git config --global core.editor "vim"

# Merge tool configuration
git config --global merge.tool vimdiff
git config --global mergetool.keepBackup false

# Default push behavior
git config --global push.default simple

Common Workflows

Feature Branch Workflow

# Start feature
git checkout main
git pull origin main
git checkout -b feature/new-feature

# Work and commit
git add .
git commit -m "Add new feature"

# Finish feature
git checkout main
git pull origin main
git merge feature/new-feature
git push origin main
git branch -d feature/new-feature

Hotfix Workflow

# Create hotfix
git checkout main
git pull origin main
git checkout -b hotfix/critical-fix

# Fix and commit
git add .
git commit -m "Fix critical bug"

# Deploy hotfix
git checkout main
git merge hotfix/critical-fix
git push origin main
git tag -a v1.0.1 -m "Hotfix release"
git push origin v1.0.1
git branch -d hotfix/critical-fix

Troubleshooting

# Common fixes
git reset --hard HEAD          # Discard all changes
git clean -fd                  # Remove untracked files
git checkout .                 # Restore all files

# Fix "detached HEAD"
git checkout main              # Return to branch

# Fix merge conflicts
git status                     # See conflicted files
# Edit files to resolve conflicts
git add resolved-file.txt
git commit

# Undo last commit (keep changes)
git reset --soft HEAD~1

# Change last commit message
git commit --amend -m "New message"

Keyboard Shortcuts

# Terminal shortcuts
Ctrl+C          # Cancel current command
Ctrl+L          # Clear screen
Tab             # Auto-complete
Up/Down arrows  # Command history

# In Git log/diff viewer
q               # Quit
j/k             # Navigate up/down
/search         # Search forward
?search         # Search backward
Space           # Page down
b               # Page up

Status Indicators

# git status --short output
M  file.txt     # Modified (staged)
 M file.txt     # Modified (not staged)
A  file.txt     # Added (staged)
D  file.txt     # Deleted (staged)
R  file.txt     # Renamed
C  file.txt     # Copied
U  file.txt     # Unmerged
?? file.txt     # Untracked
!! file.txt     # Ignored

Date Formats

# Relative dates
git log --since="2 hours ago"
git log --since="1 day ago"
git log --since="1 week ago"
git log --since="1 month ago"
git log --since="1 year ago"

# Absolute dates
git log --since="2023-01-01"
git log --since="Jan 1 2023"
git log --before="2023-12-31"

Quick Tips

Pro Tips:
  • Use tab completion for commands and branch names
  • git checkout - switches to previous branch
  • git add -p for interactive staging
  • git commit --fixup creates fixup commits for rebase
  • git log --follow file.txt tracks file renames
  • git stash -p for selective stashing

Emergency Commands

Emergency Recovery:
# Lost work recovery
git reflog                     # Find lost commits
git reset --hard <commit>     # Restore to commit

# Corrupted repository
git fsck --full               # Check integrity
git gc --prune=now           # Clean up

# Wrong commit/branch
git reset --soft HEAD~1      # Undo commit, keep changes
git checkout <correct-branch> # Switch branch
git cherry-pick <commit>     # Move commit

This cheat sheet covers the most commonly used Git commands and workflows. Keep it handy for quick reference during development work. For detailed explanations, refer to the full Git tutorial sections.