Git Commands Cheatsheet
Table of Contents
- Configuration
- Repository Basics
- Branching
- Staging & Committing
- Remote Operations
- Viewing History
- Undoing Changes
- Merging
- Rebasing
- Stashing
- Tagging
- Git Workflows
- Advanced Operations
- Git Hooks
- Troubleshooting
- Interview Scenarios
Configuration
1. Set User Information
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"2. Set Default Editor
git config --global core.editor "vim"
git config --global core.editor "code --wait" # VS Code3. View Configuration
git config --list
git config --global --list
git config --local --list
git config user.name # Get specific value4. Set 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
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
git config --global core.autocrlf input # Linux/Mac
git config --global core.autocrlf true # Windows6. Set Default Branch Name
git config --global init.defaultBranch mainRepository Basics
7. Initialize Repository
git init
git init my-project
git init --bare # Create bare repository for remote8. Clone Repository
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.git9. Check Status
git status
git status -s # Short format
git status -sb # Short format with branch10. Add Remote
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 info11. Change Remote URL
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 SSH12. Remove Remote
git remote remove origin
git remote rm upstreamBranching
13. List Branches
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 info14. Create Branch
git branch feature-name
git branch feature-name commit-hash # From specific commit15. Switch Branch
git checkout branch-name
git switch branch-name # Git 2.23+16. Create and Switch Branch
git checkout -b feature-name
git switch -c feature-name # Git 2.23+
git checkout -b feature-name origin/feature-name # Track remote17. Delete Branch
git branch -d feature-name # Safe delete (merged only)
git branch -D feature-name # Force delete
git push origin --delete feature-name # Delete remote branch18. Rename Branch
git branch -m old-name new-name
git branch -m new-name # Rename current branch19. Track Remote Branch
git branch --set-upstream-to=origin/main main
git branch -u origin/main # Short formStaging & Committing
20. Stage Files
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
git reset HEAD file.txt
git restore --staged file.txt # Git 2.23+
git reset HEAD . # Unstage all22. Commit Changes
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 message23. Commit Empty
git commit --allow-empty -m "Trigger CI"24. Sign Commits
git commit -S -m "Signed commit"
git config --global commit.gpgsign true # Always signRemote Operations
25. Fetch Changes
git fetch
git fetch origin
git fetch --all # All remotes
git fetch --prune # Remove deleted remote branches
git fetch origin branch-name26. Pull Changes
git pull
git pull origin main
git pull --rebase # Rebase instead of merge
git pull --ff-only # Fast-forward only27. Push Changes
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 tags28. Push to Multiple Remotes
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.gitViewing History
29. View Commit History
git log
git log --oneline
git log --oneline --graph
git log --oneline --graph --all
git log --oneline --decorate30. View Detailed History
git log -p # Show patches/diffs
git log -p -2 # Last 2 commits
git log --stat # Show file statistics
git log --shortstat # Abbreviated stats31. Filter History
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 file32. Format Log Output
git log --pretty=format:"%h - %an, %ar : %s"
git log --pretty=format:"%h %s" --graph
git log --oneline --graph --all --decorate33. Show Specific Commit
git show commit-hash
git show HEAD
git show HEAD~3 # 3 commits before HEAD
git show branch-name:file.txt # File from specific branch34. Compare Changes
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 only35. Blame (Author of Each Line)
git blame file.txt
git blame -L 10,20 file.txt # Specific lines
git blame -C file.txt # Detect moved/copied linesUndoing Changes
36. Discard Working Directory Changes
git checkout -- file.txt
git restore file.txt # Git 2.23+
git checkout . # Discard all changes37. Reset Commits
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 commit38. Revert Commit
git revert commit-hash
git revert HEAD
git revert HEAD~3
git revert --no-commit commit-hash # Stage revert without committing39. Clean Untracked Files
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 files40. Restore File from Past
git checkout commit-hash -- file.txt
git restore --source=commit-hash file.txtMerging
41. Merge Branch
git merge feature-branch
git merge --no-ff feature-branch # Create merge commit
git merge --squash feature-branch # Squash commits42. Merge Strategies
git merge -s recursive feature-branch
git merge -s ours feature-branch # Keep our version
git merge -X theirs feature-branch # Prefer their changes43. Abort Merge
git merge --abort44. View Merge Conflicts
git diff
git diff --name-only --diff-filter=U # List conflicted files
git status45. Resolve Conflicts
# 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 versionRebasing
46. Rebase Branch
git rebase main
git rebase origin/main
git rebase -i HEAD~5 # Interactive rebase last 5 commits47. Rebase Options
# 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 commit48. Continue/Abort Rebase
git rebase --continue
git rebase --skip
git rebase --abort49. Rebase onto Different Branch
git rebase --onto new-base old-base feature-branch50. Preserve Merge Commits
git rebase -p main # Deprecated
git rebase --rebase-merges main # Git 2.18+Stashing
51. Stash Changes
git stash
git stash save "Work in progress"
git stash -u # Include untracked files
git stash -a # Include ignored files52. List Stashes
git stash list
git stash show # Show latest stash
git stash show stash@{1}
git stash show -p # Show diff53. Apply Stash
git stash apply
git stash apply stash@{1}
git stash pop # Apply and remove54. Drop Stash
git stash drop
git stash drop stash@{1}
git stash clear # Remove all stashes55. Create Branch from Stash
git stash branch new-branch-name
git stash branch new-branch stash@{1}Tagging
56. Create Lightweight Tag
git tag v1.0.0
git tag v1.0.0 commit-hash57. Create Annotated Tag
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
git tag
git tag -l "v1.*" # Pattern matching
git show v1.0.0 # Show tag details59. Push Tags
git push origin v1.0.0
git push origin --tags # Push all tags
git push --follow-tags # Push commits and tags60. Delete Tags
git tag -d v1.0.0
git push origin --delete v1.0.0 # Delete remote tag
git push origin :refs/tags/v1.0.0 # AlternativeGit Workflows
61. GitFlow Workflow
# 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-bug62. Trunk-Based Development
# 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-12363. Forking Workflow
# 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 GitHubAdvanced Operations
64. Cherry-Pick Commits
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 --abort65. Bisect (Find Bug)
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 reset66. Submodules
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.git67. Subtree
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 main68. Archive
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.zip69. Bundle (Offline Transfer)
git bundle create repo.bundle --all
git clone repo.bundle my-repo
git bundle create repo.bundle HEAD main70. Worktrees (Multiple Working Directories)
git worktree add ../feature-branch feature-branch
git worktree list
git worktree remove ../feature-branch
git worktree prune71. Sparse Checkout
git sparse-checkout init
git sparse-checkout set folder1 folder2
git sparse-checkout add folder3
git sparse-checkout list72. Filter-Branch (Rewrite History)
# 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 "$@"
' HEAD73. Reflog (Recovery)
git reflog
git reflog show HEAD
git reflog show branch-name
git reset --hard HEAD@{2} # Restore from reflog74. Shallow Clone Operations
git clone --depth 1 https://github.com/user/repo.git
git fetch --depth=100 # Deepen history
git fetch --unshallow # Convert to full clone75. Large File Storage (LFS)
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
# .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 build77. Server-Side Hooks
# hooks/pre-receive
#!/bin/bash
# Reject commits with TODO
# hooks/update
#!/bin/bash
# Check branch permissions
# hooks/post-receive
#!/bin/bash
# Trigger deployment78. Install Hooks
# Make executable
chmod +x .git/hooks/pre-commit
# Share hooks (commit to repo)
mkdir .githooks
git config core.hooksPath .githooksTroubleshooting
79. Fix Detached HEAD
git branch temp-branch
git checkout main
git merge temp-branch80. Recover Deleted Branch
git reflog
git checkout -b recovered-branch commit-hash81. Undo Force Push
git reflog
git reset --hard commit-hash-before-force-push
git push --force-with-lease82. Fix Wrong Commit Branch
# 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-branch83. Remove Sensitive Data
# 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 --aggressive84. Fix Line Endings
git config core.autocrlf true
git rm --cached -r .
git reset --hard85. Reduce Repository Size
git gc --aggressive --prune=now
git repack -a -d --depth=250 --window=25086. Find Large Files
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 1087. Speed Up Operations
git config --global core.preloadindex true
git config --global core.fscache true
git config --global gc.auto 256
git config --global feature.manyFiles trueInterview Scenarios
Scenario 1: Accidental Commit to Main
Question: You committed to main instead of a feature branch. How do you fix it?
# 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 logScenario 2: Recover Lost Commits
Question: You ran git reset --hard and lost commits. How do you recover?
# 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 abc123Scenario 3: Merge Conflict Resolution
Question: Two developers modified the same file. How do you resolve?
# 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:
<<<<<<< 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 mergetoolScenario 4: Squash Last N Commits
Question: You have 5 commits that should be 1. How do you squash them?
# 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-leaseScenario 5: Revert Pushed Commit
Question: You pushed a bad commit. How do you revert it without rewriting history?
# Revert the commit (creates new commit)
git revert commit-hash
# Or revert multiple commits
git revert oldest-hash..newest-hash
# Push
git push origin mainScenario 6: Cherry-Pick from Another Branch
Question: Need specific commits from feature branch without merging all changes.
# 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 mainScenario 7: Split Large Commit
Question: One commit has too many changes. How do you split it?
# 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?
# 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 mainScenario 9: Remove File from History
Question: Accidentally committed secrets.txt. How do you remove it from all history?
# 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 --tagsScenario 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?
# 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 resetScenario 11: Rebase vs Merge Strategy
Question: When should you use rebase vs merge?
# 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 historyScenario 12: Partial File Commit
Question: Only want to commit specific changes in a file, not all.
# 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 unstagedScenario 13: Multiple Remote Repositories
Question: Need to push to GitHub and GitLab simultaneously.
# 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 pushScenario 14: Temporary Commits During Development
Question: Need to save work frequently but clean up before PR.
# 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-leaseScenario 15: Monorepo Strategy
Question: Multiple projects in one repo. How to manage releases?
# 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/developQuick Reference
Common Workflows
# 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/xyzUseful Aliases
git config --global alias.lg "log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%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