Git Cheat Sheet: Essential Commands for Every Developer
· 12 min read
📑 Table of Contents
Git is the most widely used version control system in the world, powering millions of projects from solo side projects to enterprise applications. Whether you're a solo developer or part of a large team, knowing the essential Git commands saves time and prevents mistakes.
This comprehensive cheat sheet covers every command you'll need for daily development work, from basic operations to advanced workflows. We've organized it by task type so you can quickly find what you need when you need it.
Bookmark this page as your quick reference. For formatting your Git documentation and README files, try our Markdown Editor.
Setup & Configuration
Before your first commit, you need to configure your identity. These settings are stored globally and attached to every commit you make, so other developers know who made which changes.
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 core.editor "code --wait"
The --global flag applies these settings to all repositories on your machine. If you need different settings for a specific project, run the same commands without --global inside that repository.
Useful Configuration Options
git config --global color.ui auto # Enable colored output
git config --global core.autocrlf true # Handle line endings (Windows)
git config --global core.autocrlf input # Handle line endings (Mac/Linux)
git config --global pull.rebase false # Use merge strategy for pulls
git config --global alias.st status # Create shortcut: git st
git config --global alias.co checkout # Create shortcut: git co
git config --global alias.br branch # Create shortcut: git br
git config --global alias.ci commit # Create shortcut: git ci
Pro tip: Create aliases for commands you use frequently. The shortcuts above can save you hundreds of keystrokes per week. You can also create more complex aliases like git config --global alias.lg "log --oneline --graph --all" for a visual commit history.
Viewing and Editing Configuration
git config --list # View all settings
git config --list --show-origin # Show where each setting is defined
git config user.name # View specific setting
git config --global --edit # Edit global config in editor
Creating Repositories
There are two ways to start working with Git: initialize a new repository or clone an existing one from a remote server.
Initialize a New Repository
git init # Initialize repo in current directory
git init my-project # Create new directory with repo
git init --bare shared-repo.git # Create bare repo (for servers)
When you run git init, Git creates a hidden .git directory that stores all version control information. This directory contains your entire project history, configuration, and metadata.
Clone an Existing Repository
git clone https://github.com/user/repo.git # Clone via HTTPS
git clone [email protected]:user/repo.git # Clone via SSH
git clone <url> my-folder # Clone into specific directory
git clone --depth 1 <url> # Shallow clone (latest commit only)
git clone --branch develop <url> # Clone specific branch
Shallow clones are useful for CI/CD pipelines or when you only need the latest code without full history. They're significantly faster and use less disk space.
Quick tip: Use SSH URLs instead of HTTPS to avoid entering your password repeatedly. Set up SSH keys once and enjoy seamless authentication. GitHub, GitLab, and Bitbucket all support SSH authentication.
Basic Workflow Commands
The core Git workflow revolves around three areas: the working directory (your files), the staging area (changes ready to commit), and the repository (committed history). Understanding this flow is crucial to using Git effectively.
Checking Status
git status # Check working tree status
git status -s # Short format output
git status -sb # Short format with branch info
Run git status frequently. It shows which files are modified, staged, or untracked, and helps you understand the current state of your repository.
Staging Changes
git add file.txt # Stage a specific file
git add *.js # Stage all JavaScript files
git add . # Stage all changes
git add -A # Stage all changes (including deletions)
git add -p # Stage changes interactively (patch mode)
git add -u # Stage modified and deleted files only
The staging area (also called the index) lets you craft precise commits. You can stage only the changes you want to include, even if you've modified multiple files.
Pro tip: Use git add -p to review and stage changes in chunks. This interactive mode lets you split large changes into logical commits, making your history cleaner and easier to review. Press ? during patch mode to see all available options.
Committing Changes
git commit -m "Add user authentication" # Commit with message
git commit -am "Fix login bug" # Stage tracked files + commit
git commit --amend # Modify the last commit
git commit --amend --no-edit # Amend without changing message
git commit -v # Show diff in commit message editor
Write clear, descriptive commit messages. A good format is: a short summary (50 chars or less), followed by a blank line, then a detailed explanation if needed.
Viewing Changes
git diff # Show unstaged changes
git diff --staged # Show staged changes
git diff HEAD # Show all changes since last commit
git diff branch1..branch2 # Compare two branches
git diff --stat # Show change statistics
git diff --word-diff # Show word-level differences
Branching & Merging
Branches are one of Git's most powerful features. They let you work on features, fixes, or experiments in isolation without affecting the main codebase.
Branch Management
git branch # List local branches
git branch -a # List all branches (local + remote)
git branch feature-login # Create new branch
git branch -d feature-login # Delete branch (safe)
git branch -D feature-login # Force delete branch
git branch -m old-name new-name # Rename branch
git branch -vv # Show branches with tracking info
Switching Branches
git checkout feature-login # Switch to branch
git checkout -b feature-signup # Create and switch to new branch
git checkout - # Switch to previous branch
git switch feature-login # Modern way to switch branches
git switch -c feature-signup # Create and switch (modern syntax)
The git switch command was introduced in Git 2.23 as a clearer alternative to git checkout, which has multiple purposes. Both work identically for switching branches.
Merging Branches
git merge feature-login # Merge branch into current branch
git merge --no-ff feature-login # Force merge commit (no fast-forward)
git merge --squash feature-login # Squash commits into one
git merge --abort # Cancel merge in progress
When you merge, Git combines the changes from two branches. If both branches modified the same lines, you'll get a merge conflict that needs manual resolution.
Resolving Merge Conflicts
When conflicts occur, Git marks the conflicting sections in your files:
<<<<<<< HEAD
Your current changes
=======
Incoming changes from the branch being merged
>>>>>>> feature-branch
To resolve conflicts:
- Open the conflicting files and edit them to resolve the conflicts
- Remove the conflict markers (
<<<<<<<,=======,>>>>>>>) - Stage the resolved files with
git add - Complete the merge with
git commit
git status # See which files have conflicts
git add resolved-file.js # Mark conflict as resolved
git merge --continue # Continue merge after resolving
git merge --abort # Give up and start over
Pro tip: Use a visual merge tool to resolve conflicts more easily. Configure one with git config --global merge.tool <tool-name> (options include meld, kdiff3, vimdiff, or your IDE's built-in tool), then run git mergetool when conflicts occur.
Rebasing
git rebase main # Rebase current branch onto main
git rebase -i HEAD~3 # Interactive rebase last 3 commits
git rebase --continue # Continue after resolving conflicts
git rebase --abort # Cancel rebase in progress
git rebase --skip # Skip current commit during rebase
Rebasing rewrites history by moving your commits to a new base. It creates a cleaner, linear history but should never be done on public branches that others are using.
Remote Operations
Remote repositories are versions of your project hosted on the internet or network. They enable collaboration and backup.
Managing Remotes
git remote # List remote connections
git remote -v # List remotes with URLs
git remote add origin <url> # Add new remote
git remote remove origin # Remove remote
git remote rename origin upstream # Rename remote
git remote set-url origin <new-url> # Change remote URL
git remote show origin # Show detailed remote info
Fetching and Pulling
git fetch # Download remote changes
git fetch origin # Fetch from specific remote
git fetch --all # Fetch from all remotes
git fetch --prune # Remove deleted remote branches
git pull # Fetch and merge remote changes
git pull --rebase # Fetch and rebase instead of merge
git pull origin main # Pull specific branch
The difference between fetch and pull: fetch downloads changes but doesn't modify your working directory, while pull fetches and immediately merges the changes.
Pushing Changes
git push # Push to default remote/branch
git push origin main # Push to specific remote/branch
git push -u origin feature-login # Push and set upstream tracking
git push --all # Push all branches
git push --tags # Push all tags
git push --force # Force push (dangerous!)
git push --force-with-lease # Safer force push
Warning: Never use --force on shared branches. It overwrites remote history and can cause data loss for your team. If you must force push, use --force-with-lease which fails if someone else pushed changes you don't have.
Working with Tags
git tag # List all tags
git tag v1.0.0 # Create lightweight tag
git tag -a v1.0.0 -m "Release version 1.0" # Create annotated tag
git tag -d v1.0.0 # Delete local tag
git push origin v1.0.0 # Push specific tag
git push origin --delete v1.0.0 # Delete remote tag
git checkout v1.0.0 # Checkout specific tag
Viewing History & Logs
Git's log commands help you understand what happened in your project, who made changes, and when.
Basic Log Commands
git log # Show commit history
git log --oneline # Compact one-line format
git log --graph # Show branch graph
git log --all # Show all branches
git log --oneline --graph --all # Combined visual history
git log -n 5 # Show last 5 commits
git log --since="2 weeks ago" # Commits from last 2 weeks
git log --until="2024-01-01" # Commits until date
git log --author="John" # Commits by specific author
Advanced Log Filtering
git log --grep="bug" # Search commit messages
git log -S "function_name" # Search code changes (pickaxe)
git log --follow file.txt # Show history including renames
git log main..feature # Commits in feature not in main
git log --stat # Show files changed in each commit
git log -p # Show full diff for each commit
git log --pretty=format:"%h - %an, %ar : %s" # Custom format
Viewing Specific Changes
git show HEAD # Show last commit
git show abc123 # Show specific commit
git show HEAD~3 # Show 3 commits ago
git show main:file.txt # Show file from specific branch
git blame file.txt # Show who changed each line
git blame -L 10,20 file.txt # Blame specific line range
Pro tip: Create an alias for your favorite log format. Try 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" for a beautiful, informative log display.
Undoing Changes
Mistakes happen. Git provides multiple ways to undo changes depending on what you need to fix.
Unstaging Files
git reset HEAD file.txt # Unstage file (keep changes)
git reset HEAD # Unstage all files
git restore --staged file.txt # Modern way to unstage
Discarding Changes
git checkout -- file.txt # Discard changes in working directory
git restore file.txt # Modern way to discard changes
git restore . # Discard all changes
git clean -fd # Remove untracked files and directories
git clean -fdn # Dry run (preview what will be deleted)
Resetting Commits
git reset --soft HEAD~1 # Undo commit, keep changes staged
git reset --mixed HEAD~1 # Undo commit, unstage changes
git reset --hard HEAD~1 # Undo commit, discard changes
git reset --hard origin/main # Reset to match remote branch
| Reset Type | Commit History | Staging Area | Working Directory | Use Case |
|---|---|---|---|---|
--soft |
Reset | Unchanged | Unchanged | Redo commit with different message or changes |
--mixed |
Reset | Reset | Unchanged | Unstage files but keep changes (default) |
--hard |
Reset | Reset | Reset | Completely discard commits and changes |
Reverting Commits
git revert HEAD # Create new commit that undoes last commit
git revert abc123 # Revert specific commit
git revert HEAD~3..HEAD # Revert range of commits
git revert --no-commit HEAD~3..HEAD # Revert multiple commits at once
Unlike reset, revert creates new commits that undo changes. This is safer for shared branches because it doesn't rewrite history.
Recovering Lost Commits
git reflog # Show history of HEAD movements
git reflog show branch-name # Show reflog for specific branch
git checkout abc123 # Recover commit from reflog
git reset --hard abc123 # Reset to recovered commit
Quick tip: The reflog is your safety net. Even if you accidentally delete commits with git reset --hard, they're still in the reflog for about 90 days. Use git reflog to find the commit hash, then restore it.
Stashing Work
Stashing lets you save uncommitted changes temporarily so you can switch branches or pull updates without committing incomplete work.
Basic Stashing
git stash # Stash current changes
git stash save "Work in progress on feature" # Stash with description
git stash -u # Include untracked files
git stash -a # Include all files (even ignored)
git stash list # List all stashes
git stash show # Show changes in latest stash
git stash show -p # Show full diff of latest stash
Applying Stashes
git stash pop # Apply and remove latest stash
git stash apply # Apply latest stash (keep in list)
git stash apply stash@{2} # Apply specific stash
git stash drop # Delete latest stash
git stash drop stash@{2} # Delete specific stash
git stash clear # Delete all stashes
Advanced Stashing
git stash branch feature-branch # Create branch from stash
git stash --patch # Interactively stash changes
git stash show stash@{1} --stat # Show files changed in stash
Stashes are stored in a stack (last in, first out). The most recent stash is stash@{0}, the one before that is stash@{1}, and so on.
Advanced Commands
These commands handle more complex scenarios and workflows that you'll encounter as you become more proficient with Git.
Cherry-Picking
git cherry-pick abc123 # Apply specific commit to current branch
git cherry-pick abc123 def456 # Cherry-pick multiple commits
git cherry-pick --no-commit abc123 # Apply changes without committing
git cherry-pick --continue # Continue after resolving conflicts
git cherry-pick --abort # Cancel cherry-pick
Cherry-picking is useful when you need a specific fix from another branch but don't want to merge the entire branch.
Bisecting
git bisect start # Start bisect session
git bisect bad # Mark current commit as bad
git bisect good abc123 # Mark known good commit
git bisect reset # End bisect session
git bisect run npm test # Automate bisect with test script
Bisecting uses binary search to find which commit introduced a bug. Git checks out commits for you to test, dramatically speeding up bug hunting.
Submodules
git submodule add <url> path/to/submodule # Add submodule
git submodule init # Initialize submodules
git submodule update # Update submodules
git submodule update --remote # Update to latest remote version
git clone --recurse-submodules <url> # Clone with submodules
Working with Patches
git format-patch -1 HEAD # Create patch from last commit
git format-patch main..feature # Create patches for branch
git apply patch-file.patch # Apply patch
git am patch-file.patch # Apply patch as commit
Searching and Finding
git grep "search term" # Search working directory
git grep "search term" v1.0 # Search specific version
git log -S "function_name" # Find commits that added/removed text
git log --all --full-history -- path/to/file # Find deleted file in history
.gitignore Patterns
The .gitignore file tells Git which files to ignore. This prevents committing build artifacts, dependencies, secrets, and other files that shouldn't be in version control.
Common Patterns
# Dependencies
node_modules/
vendor/
*.gem
# Build outputs
dist/
build/
*.o
*.exe
# IDE and editor files
.vscode/
.idea/
*.swp
*.swo
*~
# Operating system files
.DS_Store
Thumbs.db
desktop.ini
# Environment and secrets
.env
.env.local
*.key
*.pem
config/secrets.yml
# Logs
*.log
logs/
npm-debug.log*
# Temporary files
tmp/
temp/
*.tmp
*.cache
Pattern Syntax
| Pattern | Description | Example |
|---|---|---|
*.log |
Ignore all files with extension | Ignores error.log, debug.log |
temp/ |
Ignore directory and contents | Ignores temp/ folder |
**/logs |
Ignore in any directory | Ignores logs/ anywhere in tree |
!important.log |
Exception (don't ignore) | Track important.log despite *.log |
doc/*.txt |
Ignore in specific directory only | Ignores doc/notes.txt but not doc/sub/notes.txt |
doc/**/*.txt |
Ignore in directory and subdirectories | Ignores all .txt files under doc/ |
Managing Ignored Files
git status --ignored # Show ignored files
git check-ignore -v file.txt # Check why file is ignored
git rm --cached file.txt # Stop tracking file (keep local copy)
git rm -r --cached . # Untrack all files
git add -f file.log # Force add ignored file
Pro tip: Use a global gitignore file for personal preferences like IDE files. Set it up with git config --global core.excludesfile ~/.gitignore_global. This keeps project .gitignore files focused on project-specific patterns.
Template Generators
Don't write .gitignore files from scratch. Use our Gitignore Generator to create comprehensive ignore files for your tech stack, or visit gitignore.io for community templates.
Common Issues & Troubleshooting
Even experienced developers encounter Git problems. Here are solutions to the most common issues.
Fixing "Detached HEAD" State
This happens when you checkout a specific commit instead of a branch:
git checkout main # Return to main branch
git checkout -b new-branch # Create branch from current position
git switch - # Return to previous branch
Resolving "Diverged Branches"
When your local and remote branches have different commits:
git pull --rebase origin main # Rebase your changes on top
git pull --no-rebase origin main # Merge remote changes
git push --force-with-lease # Push after rebasing (if needed)
Fixing Committed Secrets
If you accidentally committed passwords or API keys:
git reset --soft HEAD~1 # Undo commit (keep changes)
# Edit files to remove secrets
git add .
git commit -m "Add feature (secrets removed)"
# If already pushed, you need to rewrite history:
git filter-branch --force --index-filter \
"git rm --cached --ignore-unmatch path/to/secret" \
--prune-empty --tag-name-filter cat -- --all
Important: If secrets were pushed to a public repository, consider them compromised. Rotate the credentials immediately.
Recovering from Bad Merge
git merge --abort # Cancel merge in progress
git reset --hard HEAD # Discard all merge changes
git reset --hard ORIG_HEAD # Undo completed merge
Fixing Line Ending Issues
Windows uses CRLF, Unix uses LF. This can cause problems:
git config --global core.autocrlf true # Windows: convert to CRLF on checkout
git config --global core.autocrlf input # Mac/Linux: convert to LF on commit
git add --renormalize . # Fix existing files
Dealing with Large Files
Git struggles with large binary files. If you've committed large files by mistake:
git rm --cached large-file.zip # Stop tracking file
# Add to .gitignore
git commit -m "Remove large file"
# To remove from