# Git Commands Cheatsheet 

## Table of Contents
1. [Configuration](#configuration)
2. [Repository Basics](#repository-basics)
3. [Branching](#branching)
4. [Staging & Committing](#staging--committing)
5. [Remote Operations](#remote-operations)
6. [Viewing History](#viewing-history)
7. [Undoing Changes](#undoing-changes)
8. [Merging](#merging)
9. [Rebasing](#rebasing)
10. [Stashing](#stashing)
11. [Tagging](#tagging)
12. [Git Workflows](#git-workflows)
13. [Advanced Operations](#advanced-operations)
14. [Git Hooks](#git-hooks)
15. [Troubleshooting](#troubleshooting)
16. [Interview Scenarios](#interview-scenarios)

---

## Configuration

### 1. Set User Information
```bash
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
```

### 2. Set Default Editor
```bash
git config --global core.editor "vim"
git config --global core.editor "code --wait"  # VS Code
```

### 3. View Configuration
```bash
git config --list
git config --global --list
git config --local --list
git config user.name  # Get specific value
```

### 4. Set Aliases
```bash
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status
git config --global alias.unstage 'reset HEAD --'
git config --global alias.last 'log -1 HEAD'
git config --global alias.visual '!gitk'
```

### 5. Configure Line Endings
```bash
git config --global core.autocrlf input   # Linux/Mac
git config --global core.autocrlf true    # Windows
```

### 6. Set Default Branch Name
```bash
git config --global init.defaultBranch main
```

---

## Repository Basics

### 7. Initialize Repository
```bash
git init
git init my-project
git init --bare  # Create bare repository for remote
```

### 8. Clone Repository
```bash
git clone https://github.com/user/repo.git
git clone git@github.com:user/repo.git  # SSH
git clone https://github.com/user/repo.git my-folder
git clone --depth 1 https://github.com/user/repo.git  # Shallow clone
git clone --branch develop https://github.com/user/repo.git
```

### 9. Check Status
```bash
git status
git status -s   # Short format
git status -sb  # Short format with branch
```

### 10. Add Remote
```bash
git remote add origin https://github.com/user/repo.git
git remote add upstream https://github.com/original/repo.git
git remote -v  # View remotes
git remote show origin  # Detailed info
```

### 11. Change Remote URL
```bash
git remote set-url origin https://github.com/user/new-repo.git
git remote set-url origin git@github.com:user/repo.git  # Switch to SSH
```

### 12. Remove Remote
```bash
git remote remove origin
git remote rm upstream
```

---

## Branching

### 13. List Branches
```bash
git branch              # Local branches
git branch -r           # Remote branches
git branch -a           # All branches
git branch -v           # With last commit
git branch -vv          # With tracking info
```

### 14. Create Branch
```bash
git branch feature-name
git branch feature-name commit-hash  # From specific commit
```

### 15. Switch Branch
```bash
git checkout branch-name
git switch branch-name  # Git 2.23+
```

### 16. Create and Switch Branch
```bash
git checkout -b feature-name
git switch -c feature-name  # Git 2.23+
git checkout -b feature-name origin/feature-name  # Track remote
```

### 17. Delete Branch
```bash
git branch -d feature-name   # Safe delete (merged only)
git branch -D feature-name   # Force delete
git push origin --delete feature-name  # Delete remote branch
```

### 18. Rename Branch
```bash
git branch -m old-name new-name
git branch -m new-name  # Rename current branch
```

### 19. Track Remote Branch
```bash
git branch --set-upstream-to=origin/main main
git branch -u origin/main  # Short form
```

---

## Staging & Committing

### 20. Stage Files
```bash
git add file.txt
git add .               # All files in current directory
git add -A              # All files in repository
git add *.js            # Pattern matching
git add -p              # Interactive staging (patch mode)
```

### 21. Unstage Files
```bash
git reset HEAD file.txt
git restore --staged file.txt  # Git 2.23+
git reset HEAD .               # Unstage all
```

### 22. Commit Changes
```bash
git commit -m "Commit message"
git commit -am "Message"  # Add and commit tracked files
git commit --amend        # Amend last commit
git commit --amend --no-edit  # Amend without changing message
```

### 23. Commit Empty
```bash
git commit --allow-empty -m "Trigger CI"
```

### 24. Sign Commits
```bash
git commit -S -m "Signed commit"
git config --global commit.gpgsign true  # Always sign
```

---

## Remote Operations

### 25. Fetch Changes
```bash
git fetch
git fetch origin
git fetch --all           # All remotes
git fetch --prune         # Remove deleted remote branches
git fetch origin branch-name
```

### 26. Pull Changes
```bash
git pull
git pull origin main
git pull --rebase         # Rebase instead of merge
git pull --ff-only        # Fast-forward only
```

### 27. Push Changes
```bash
git push
git push origin main
git push -u origin feature-name  # Set upstream and push
git push --force          # Force push (dangerous!)
git push --force-with-lease  # Safer force push
git push --all            # Push all branches
git push --tags           # Push all tags
```

### 28. Push to Multiple Remotes
```bash
git remote set-url --add --push origin https://github.com/user/repo1.git
git remote set-url --add --push origin https://github.com/user/repo2.git
```

---

## Viewing History

### 29. View Commit History
```bash
git log
git log --oneline
git log --oneline --graph
git log --oneline --graph --all
git log --oneline --decorate
```

### 30. View Detailed History
```bash
git log -p              # Show patches/diffs
git log -p -2           # Last 2 commits
git log --stat          # Show file statistics
git log --shortstat     # Abbreviated stats
```

### 31. Filter History
```bash
git log --since="2 weeks ago"
git log --until="2024-01-01"
git log --author="John"
git log --grep="fix"    # Search commit messages
git log -S "function_name"  # Search code changes (pickaxe)
git log -- file.txt     # Commits affecting specific file
```

### 32. Format Log Output
```bash
git log --pretty=format:"%h - %an, %ar : %s"
git log --pretty=format:"%h %s" --graph
git log --oneline --graph --all --decorate
```

### 33. Show Specific Commit
```bash
git show commit-hash
git show HEAD
git show HEAD~3         # 3 commits before HEAD
git show branch-name:file.txt  # File from specific branch
```

### 34. Compare Changes
```bash
git diff                # Unstaged changes
git diff --staged       # Staged changes
git diff HEAD           # All changes
git diff branch1 branch2
git diff commit1 commit2
git diff --stat         # Summary only
```

### 35. Blame (Author of Each Line)
```bash
git blame file.txt
git blame -L 10,20 file.txt  # Specific lines
git blame -C file.txt        # Detect moved/copied lines
```

---

## Undoing Changes

### 36. Discard Working Directory Changes
```bash
git checkout -- file.txt
git restore file.txt    # Git 2.23+
git checkout .          # Discard all changes
```

### 37. Reset Commits
```bash
git reset --soft HEAD~1   # Keep changes staged
git reset --mixed HEAD~1  # Keep changes unstaged (default)
git reset --hard HEAD~1   # Discard changes (dangerous!)
git reset commit-hash     # Reset to specific commit
```

### 38. Revert Commit
```bash
git revert commit-hash
git revert HEAD
git revert HEAD~3
git revert --no-commit commit-hash  # Stage revert without committing
```

### 39. Clean Untracked Files
```bash
git clean -n            # Dry run
git clean -f            # Remove untracked files
git clean -fd           # Remove files and directories
git clean -fX           # Remove ignored files only
git clean -fx           # Remove untracked and ignored files
```

### 40. Restore File from Past
```bash
git checkout commit-hash -- file.txt
git restore --source=commit-hash file.txt
```

---

## Merging

### 41. Merge Branch
```bash
git merge feature-branch
git merge --no-ff feature-branch  # Create merge commit
git merge --squash feature-branch # Squash commits
```

### 42. Merge Strategies
```bash
git merge -s recursive feature-branch
git merge -s ours feature-branch      # Keep our version
git merge -X theirs feature-branch    # Prefer their changes
```

### 43. Abort Merge
```bash
git merge --abort
```

### 44. View Merge Conflicts
```bash
git diff
git diff --name-only --diff-filter=U  # List conflicted files
git status
```

### 45. Resolve Conflicts
```bash
# Edit conflicted files, then:
git add file.txt
git commit

# Or use tools:
git mergetool
git checkout --ours file.txt    # Use our version
git checkout --theirs file.txt  # Use their version
```

---

## Rebasing

### 46. Rebase Branch
```bash
git rebase main
git rebase origin/main
git rebase -i HEAD~5    # Interactive rebase last 5 commits
```

### 47. Rebase Options
```bash
# During interactive rebase:
# pick   = use commit
# reword = use commit, but edit message
# edit   = use commit, but stop for amending
# squash = use commit, but meld into previous
# fixup  = like squash, but discard message
# drop   = remove commit
```

### 48. Continue/Abort Rebase
```bash
git rebase --continue
git rebase --skip
git rebase --abort
```

### 49. Rebase onto Different Branch
```bash
git rebase --onto new-base old-base feature-branch
```

### 50. Preserve Merge Commits
```bash
git rebase -p main  # Deprecated
git rebase --rebase-merges main  # Git 2.18+
```

---

## Stashing

### 51. Stash Changes
```bash
git stash
git stash save "Work in progress"
git stash -u            # Include untracked files
git stash -a            # Include ignored files
```

### 52. List Stashes
```bash
git stash list
git stash show          # Show latest stash
git stash show stash@{1}
git stash show -p       # Show diff
```

### 53. Apply Stash
```bash
git stash apply
git stash apply stash@{1}
git stash pop           # Apply and remove
```

### 54. Drop Stash
```bash
git stash drop
git stash drop stash@{1}
git stash clear         # Remove all stashes
```

### 55. Create Branch from Stash
```bash
git stash branch new-branch-name
git stash branch new-branch stash@{1}
```

---

## Tagging

### 56. Create Lightweight Tag
```bash
git tag v1.0.0
git tag v1.0.0 commit-hash
```

### 57. Create Annotated Tag
```bash
git tag -a v1.0.0 -m "Release version 1.0.0"
git tag -a v1.0.0 commit-hash -m "Message"
```

### 58. List Tags
```bash
git tag
git tag -l "v1.*"       # Pattern matching
git show v1.0.0         # Show tag details
```

### 59. Push Tags
```bash
git push origin v1.0.0
git push origin --tags  # Push all tags
git push --follow-tags  # Push commits and tags
```

### 60. Delete Tags
```bash
git tag -d v1.0.0
git push origin --delete v1.0.0  # Delete remote tag
git push origin :refs/tags/v1.0.0  # Alternative
```

---

## Git Workflows

### 61. GitFlow Workflow
```bash
# Feature development
git checkout -b feature/new-feature develop
# Work and commit
git checkout develop
git merge --no-ff feature/new-feature
git branch -d feature/new-feature

# Release
git checkout -b release/1.0 develop
# Finalize release
git checkout main
git merge --no-ff release/1.0
git tag -a v1.0 -m "Version 1.0"
git checkout develop
git merge --no-ff release/1.0
git branch -d release/1.0

# Hotfix
git checkout -b hotfix/critical-bug main
# Fix and commit
git checkout main
git merge --no-ff hotfix/critical-bug
git tag -a v1.0.1
git checkout develop
git merge --no-ff hotfix/critical-bug
git branch -d hotfix/critical-bug
```

### 62. Trunk-Based Development
```bash
# Always work on main or short-lived feature branches
git checkout -b feature-123
# Small, frequent commits
git push origin feature-123
# Quick merge to main
git checkout main
git merge feature-123
git branch -d feature-123
```

### 63. Forking Workflow
```bash
# Fork repository on GitHub, then:
git clone git@github.com:yourname/repo.git
git remote add upstream git@github.com:original/repo.git

# Keep fork updated
git fetch upstream
git checkout main
git merge upstream/main
git push origin main

# Create feature branch
git checkout -b feature-name
git push origin feature-name
# Create pull request on GitHub
```

---

## Advanced Operations

### 64. Cherry-Pick Commits
```bash
git cherry-pick commit-hash
git cherry-pick commit1 commit2
git cherry-pick --no-commit commit-hash  # Stage without committing
git cherry-pick --continue
git cherry-pick --abort
```

### 65. Bisect (Find Bug)
```bash
git bisect start
git bisect bad          # Current commit is bad
git bisect good v1.0    # Known good commit
# Git checks out middle commit, test it
git bisect good  # or bad
# Repeat until found
git bisect reset
```

### 66. Submodules
```bash
git submodule add https://github.com/user/repo.git path/to/submodule
git submodule init
git submodule update
git submodule update --remote  # Update to latest
git clone --recurse-submodules https://github.com/user/repo.git
```

### 67. Subtree
```bash
git subtree add --prefix=lib/plugin https://github.com/user/repo.git main --squash
git subtree pull --prefix=lib/plugin https://github.com/user/repo.git main --squash
git subtree push --prefix=lib/plugin https://github.com/user/repo.git main
```

### 68. Archive
```bash
git archive --format=zip --output=project.zip HEAD
git archive --format=tar.gz --output=project.tar.gz HEAD
git archive --format=zip HEAD:path/to/dir > dir.zip
```

### 69. Bundle (Offline Transfer)
```bash
git bundle create repo.bundle --all
git clone repo.bundle my-repo
git bundle create repo.bundle HEAD main
```

### 70. Worktrees (Multiple Working Directories)
```bash
git worktree add ../feature-branch feature-branch
git worktree list
git worktree remove ../feature-branch
git worktree prune
```

### 71. Sparse Checkout
```bash
git sparse-checkout init
git sparse-checkout set folder1 folder2
git sparse-checkout add folder3
git sparse-checkout list
```

### 72. Filter-Branch (Rewrite History)
```bash
# Remove file from all history
git filter-branch --tree-filter 'rm -f passwords.txt' HEAD

# Change email in all commits
git filter-branch --commit-filter '
    if [ "$GIT_AUTHOR_EMAIL" = "old@example.com" ]; then
        GIT_AUTHOR_EMAIL="new@example.com"
    fi
    git commit-tree "$@"
' HEAD
```

### 73. Reflog (Recovery)
```bash
git reflog
git reflog show HEAD
git reflog show branch-name
git reset --hard HEAD@{2}  # Restore from reflog
```

### 74. Shallow Clone Operations
```bash
git clone --depth 1 https://github.com/user/repo.git
git fetch --depth=100  # Deepen history
git fetch --unshallow  # Convert to full clone
```

### 75. Large File Storage (LFS)
```bash
git lfs install
git lfs track "*.psd"
git add .gitattributes
git lfs ls-files
git lfs migrate import --include="*.zip"
```

---

## Git Hooks

### 76. Client-Side Hooks
```bash
# .git/hooks/pre-commit
#!/bin/bash
npm test

# .git/hooks/commit-msg
#!/bin/bash
# Enforce commit message format
grep -E '^(feat|fix|docs|style|refactor|test|chore): .+' "$1"

# .git/hooks/pre-push
#!/bin/bash
npm run build
```

### 77. Server-Side Hooks
```bash
# hooks/pre-receive
#!/bin/bash
# Reject commits with TODO

# hooks/update
#!/bin/bash
# Check branch permissions

# hooks/post-receive
#!/bin/bash
# Trigger deployment
```

### 78. Install Hooks
```bash
# Make executable
chmod +x .git/hooks/pre-commit

# Share hooks (commit to repo)
mkdir .githooks
git config core.hooksPath .githooks
```

---

## Troubleshooting

### 79. Fix Detached HEAD
```bash
git branch temp-branch
git checkout main
git merge temp-branch
```

### 80. Recover Deleted Branch
```bash
git reflog
git checkout -b recovered-branch commit-hash
```

### 81. Undo Force Push
```bash
git reflog
git reset --hard commit-hash-before-force-push
git push --force-with-lease
```

### 82. Fix Wrong Commit Branch
```bash
# Committed to main instead of feature branch
git branch feature-branch  # Create branch from current
git reset --hard origin/main  # Reset main
git checkout feature-branch
```

### 83. Remove Sensitive Data
```bash
# Using BFG Repo Cleaner (faster than filter-branch)
java -jar bfg.jar --delete-files passwords.txt
java -jar bfg.jar --replace-text passwords.txt
git reflog expire --expire=now --all
git gc --prune=now --aggressive
```

### 84. Fix Line Endings
```bash
git config core.autocrlf true
git rm --cached -r .
git reset --hard
```

### 85. Reduce Repository Size
```bash
git gc --aggressive --prune=now
git repack -a -d --depth=250 --window=250
```

### 86. Find Large Files
```bash
git rev-list --objects --all | \
  git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' | \
  sed -n 's/^blob //p' | \
  sort --numeric-sort --key=2 | \
  tail -n 10
```

### 87. Speed Up Operations
```bash
git config --global core.preloadindex true
git config --global core.fscache true
git config --global gc.auto 256
git config --global feature.manyFiles true
```

---

## Interview Scenarios

### Scenario 1: Accidental Commit to Main
**Question**: You committed to main instead of a feature branch. How do you fix it?

```bash
# Create branch from current state
git branch feature/my-feature

# Reset main to origin
git reset --hard origin/main

# Switch to feature branch
git checkout feature/my-feature

# Verify changes are there
git log
```

### Scenario 2: Recover Lost Commits
**Question**: You ran `git reset --hard` and lost commits. How do you recover?

```bash
# Find lost commits
git reflog

# Identify the commit hash before reset
# Recover
git reset --hard HEAD@{2}

# Or create branch from it
git checkout -b recovery-branch abc123
```

### Scenario 3: Merge Conflict Resolution
**Question**: Two developers modified the same file. How do you resolve?

```bash
# Pull latest changes
git pull origin main

# Conflict occurs
# CONFLICT (content): Merge conflict in file.txt

# View conflicted files
git status

# Edit file.txt, look for:
&lt;&lt;&lt;&lt;&lt;&lt;&lt; HEAD
Your changes
=======
Their changes
>>>>>>> branch-name

# Keep desired changes, remove markers

# Stage resolved file
git add file.txt

# Complete merge
git commit

# Or use merge tool
git mergetool
```

### Scenario 4: Squash Last N Commits
**Question**: You have 5 commits that should be 1. How do you squash them?

```bash
# Interactive rebase
git rebase -i HEAD~5

# In editor, change all except first to 'squash':
pick abc123 First commit
squash def456 Second commit
squash ghi789 Third commit
squash jkl012 Fourth commit
squash mno345 Fifth commit

# Save and edit commit message
git push --force-with-lease
```

### Scenario 5: Revert Pushed Commit
**Question**: You pushed a bad commit. How do you revert it without rewriting history?

```bash
# Revert the commit (creates new commit)
git revert commit-hash

# Or revert multiple commits
git revert oldest-hash..newest-hash

# Push
git push origin main
```

### Scenario 6: Cherry-Pick from Another Branch
**Question**: Need specific commits from feature branch without merging all changes.

```bash
# Find commits you want
git log feature-branch

# Cherry-pick them
git checkout main
git cherry-pick abc123
git cherry-pick def456

# If conflicts, resolve and continue
git add .
git cherry-pick --continue

# Push
git push origin main
```

### Scenario 7: Split Large Commit
**Question**: One commit has too many changes. How do you split it?

```bash
# Reset to previous commit, keeping changes
git reset HEAD~1

# Stage changes incrementally
git add -p  # Interactive staging

# Commit first set
git commit -m "First logical change"

# Stage and commit second set
git add -p
git commit -m "Second logical change"
```

### Scenario 8: Update Fork with Upstream
**Question**: Your fork is behind the original repo. How do you sync?

```bash
# Add upstream remote (once)
git remote add upstream https://github.com/original/repo.git

# Fetch upstream changes
git fetch upstream

# Merge into your main
git checkout main
git merge upstream/main

# Or rebase for cleaner history
git rebase upstream/main

# Push to your fork
git push origin main
```

### Scenario 9: Remove File from History
**Question**: Accidentally committed secrets.txt. How do you remove it from all history?

```bash
# Using BFG (recommended)
java -jar bfg.jar --delete-files secrets.txt
git reflog expire --expire=now --all
git gc --prune=now --aggressive
git push --force

# Or using filter-branch
git filter-branch --force --index-filter \
  'git rm --cached --ignore-unmatch secrets.txt' \
  --prune-empty --tag-name-filter cat -- --all

git push --force --all
git push --force --tags
```

### Scenario 10: Find When Bug Was Introduced
**Question**: A bug exists now but didn't in v1.0. How do you find which commit introduced it?

```bash
# Start bisect
git bisect start

# Mark current as bad
git bisect bad

# Mark known good version
git bisect good v1.0

# Git checks out middle commit
# Test the code
npm test

# Mark result
git bisect good  # or 'bad'

# Repeat until found
# Git will identify the exact commit

# Reset
git bisect reset
```

### Scenario 11: Rebase vs Merge Strategy
**Question**: When should you use rebase vs merge?

```bash
# Use MERGE when:
# - Preserving complete history is important
# - Working with public/shared branches
# - Want to see when features were integrated
git checkout main
git merge feature-branch

# Use REBASE when:
# - Want linear history
# - Working on private feature branches
# - Before creating pull request
git checkout feature-branch
git rebase main
git push --force-with-lease origin feature-branch

# Golden rule: Never rebase public history
```

### Scenario 12: Partial File Commit
**Question**: Only want to commit specific changes in a file, not all.

```bash
# Interactive staging
git add -p file.txt

# Options:
# y - stage this hunk
# n - don't stage this hunk
# s - split into smaller hunks
# e - manually edit the hunk
# q - quit

# Commit staged changes
git commit -m "Partial changes"

# Remaining changes stay unstaged
```

### Scenario 13: Multiple Remote Repositories
**Question**: Need to push to GitHub and GitLab simultaneously.

```bash
# Add multiple push URLs
git remote set-url --add --push origin https://github.com/user/repo.git
git remote set-url --add --push origin https://gitlab.com/user/repo.git

# Verify
git remote -v

# Now git push pushes to both
git push
```

### Scenario 14: Temporary Commits During Development
**Question**: Need to save work frequently but clean up before PR.

```bash
# During development - commit frequently
git add .
git commit -m "WIP: partial implementation"

# Before creating PR - clean up commits
git rebase -i origin/main

# Squash WIP commits
pick abc123 Feature: Add user authentication
fixup def456 WIP: partial implementation
fixup ghi789 WIP: fixing tests
fixup jkl012 WIP: cleanup

# Force push to feature branch
git push --force-with-lease
```

### Scenario 15: Monorepo Strategy
**Question**: Multiple projects in one repo. How to manage releases?

```bash
# Tag with project prefix
git tag -a frontend/v1.0.0 -m "Frontend Release 1.0.0"
git tag -a backend/v2.1.0 -m "Backend Release 2.1.0"

# View tags for specific project
git tag -l "frontend/*"

# Sparse checkout for CI/CD
git sparse-checkout set frontend/
npm run build

# Or use git worktrees for parallel development
git worktree add ../frontend-hotfix frontend/main
git worktree add ../backend-feature backend/develop
```

---

## Quick Reference

### Common Workflows
```bash
# Daily workflow
git pull
git checkout -b feature/xyz
# Make changes
git add .
git commit -m "message"
git push -u origin feature/xyz

# Update feature branch
git checkout feature/xyz
git rebase main
git push --force-with-lease

# Clean merge
git checkout main
git merge --no-ff feature/xyz
git push
git branch -d feature/xyz
```

### Useful Aliases
```bash
git config --global alias.lg "log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)&lt;%an>%Creset' --abbrev-commit"
git config --global alias.undo "reset --soft HEAD~1"
git config --global alias.amend "commit --amend --no-edit"
git config --global alias.cleanup "!git branch --merged | grep -v '\\*\\|main\\|develop' | xargs -n 1 git branch -d"
```

---


**Total Commands**: 87+ commands covering all Git operations
