Git is the backbone of modern software development, enabling developers worldwide to collaborate effectively and maintain robust version control systems. Whether you’re just starting your journey with Git or you’re a seasoned developer looking for a quick reference, this comprehensive cheatsheet covers everything from basic setup to advanced operations. Mastering these commands will significantly improve your development workflow and make you more productive in your daily coding tasks.
Getting Started and Configuration #
Before you can leverage Git’s powerful features, you need to properly configure your environment. These initial setup commands establish your identity and preferences across all your repositories.
Initial Setup #
Setting up your Git configuration correctly from the start ensures that all your commits are properly attributed and that your workflow matches your preferences. These global configurations apply to all repositories on your system unless overridden by local repository settings.
# Set your identity for all repositories
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
# Set your preferred text editor (vim, nano, code, etc.)
git config --global core.editor "vim"
# Enable colored output in your terminal for better readability
git config --global color.ui auto
# Store credentials temporarily to avoid repeated logins
git config --global credential.helper cache
# Set credential cache timeout (in seconds)
git config --global credential.helper 'cache --timeout=3600'
# View all configuration settings
git config --list
# View configuration with file locations
git config --list --show-origin
Repository Creation and Cloning #
Creating or obtaining a repository is your first step in any Git-based project. You can either initialize a new repository from scratch or clone an existing one from a remote source.
# Initialize a new Git repository in the current directory
git init
# Initialize with a specific initial branch name
git init -b main
# Clone an existing repository from a remote URL
git clone https://github.com/username/repository.git
# Clone a specific branch instead of the default branch
git clone -b branch-name https://github.com/username/repository.git
# Clone into a custom-named local directory
git clone https://github.com/username/repository.git custom-directory-name
# Clone with limited depth (shallow clone) for faster downloads
git clone --depth 1 https://github.com/username/repository.git
# Clone only a specific branch with limited depth
git clone --depth 1 --branch branch-name --single-branch https://github.com/username/repository.git
Daily Workflow Commands #
These commands form the core of your daily Git usage. Understanding these operations thoroughly will make your version control workflow smooth and efficient.
Basic Operations #
The fundamental operations of checking status, viewing changes, and staging files are commands you’ll use countless times every day. These commands help you understand the current state of your repository and prepare changes for commit.
# Check the current status of your repository
git status
# Get a compact, easy-to-read status output
git status -s
# Show unstaged changes in your working directory
git diff
# Show changes that have been staged for commit
git diff --staged
# Compare changes between two branches
git diff branch1..branch2
# Show changes for a specific file
git diff filename
# Add a specific file to the staging area
git add filename
# Add all modified and new files to staging
git add .
# Add all files with a specific pattern
git add *.js
# Add all files in a specific directory
git add directory/
# Add parts of a file interactively
git add -p filename
# Remove a file from both working directory and staging area
git rm filename
# Remove a file from staging but keep it in working directory
git rm --cached filename
# Remove all files matching a pattern
git rm '*.log'
# Move or rename a file and stage the change
git mv old-filename new-filename
# View what would be removed (dry run)
git clean -n
# Remove untracked files
git clean -f
# Remove untracked files and directories
git clean -fd
Committing Changes #
Commits are the fundamental units of change in Git. Each commit represents a snapshot of your project at a specific point in time, and writing clear commit messages is crucial for maintaining a understandable project history.
# Create a commit with a message
git commit -m "Add new feature for user authentication"
# Add all tracked files and commit in one step
git commit -am "Fix bug in login validation"
# Open your default editor for a detailed commit message
git commit
# Modify the most recent commit message
git commit --amend -m "Updated commit message"
# Add more changes to the most recent commit
git commit --amend --no-edit
# Create a commit with a specific author
git commit --author="Name <email@example.com>" -m "Message"
# Create an empty commit (useful for triggering CI/CD pipelines)
git commit --allow-empty -m "Trigger deployment"
# Sign commits with GPG
git commit -S -m "Signed commit message"
Branch Management #
Branches are one of Git’s most powerful features, allowing you to work on multiple features or fixes simultaneously without affecting the main codebase. Effective branch management is essential for collaborative development.
Working with Branches #
Creating, switching, and managing branches allows you to organize your work logically and keep different development streams separate until they’re ready to be integrated.
# List all local branches
git branch
# List all remote-tracking branches
git branch -r
# List all branches (local and remote)
git branch -a
# List branches with additional information (last commit)
git branch -v
# List branches that have been merged into current branch
git branch --merged
# List branches that haven't been merged yet
git branch --no-merged
# Create a new branch
git branch feature-branch-name
# Create and immediately switch to a new branch
git checkout -b feature-branch-name
# Create a new branch from a specific commit
git branch branch-name commit-hash
# Switch to an existing branch
git checkout branch-name
# Switch to the previously checked out branch
git checkout -
# Delete a branch safely (prevents deletion if unmerged)
git branch -d branch-name
# Force delete a branch regardless of merge status
git branch -D branch-name
# Rename the current branch
git branch -m new-branch-name
# Rename a different branch
git branch -m old-name new-name
# Set upstream branch for current branch
git branch --set-upstream-to=origin/branch-name
Remote Operations #
Working with remote repositories is essential for collaboration. These commands help you synchronize your local work with remote servers and collaborate with team members.
# Add a new remote repository
git remote add origin https://github.com/username/repository.git
# Add an additional remote (e.g., for forks)
git remote add upstream https://github.com/original/repository.git
# List all configured remote repositories
git remote -v
# Show detailed information about a remote
git remote show origin
# Rename a remote
git remote rename old-name new-name
# Remove a remote
git remote remove remote-name
# Push commits to remote repository
git push origin branch-name
# Push and set upstream tracking branch
git push -u origin branch-name
# Push all branches to remote
git push --all origin
# Push tags to remote
git push origin tag-name
# Push all tags to remote
git push origin --tags
# Delete a remote branch
git push origin --delete branch-name
# Fetch changes from remote without merging
git fetch origin
# Fetch from all remotes
git fetch --all
# Fetch and prune deleted remote branches
git fetch --prune
# Pull changes from remote and merge
git pull origin branch-name
# Pull with rebase instead of merge
git pull --rebase origin branch-name
# Pull from all remotes
git pull --all
History and Logs #
Understanding your project’s history is crucial for debugging, code review, and understanding how your codebase evolved. Git provides powerful tools for exploring and analyzing commit history.
Viewing History #
Git’s logging capabilities are extensive, allowing you to filter and format commit history in numerous ways to find exactly the information you need.
# Show full commit history
git log
# Show compact one-line-per-commit history
git log --oneline
# Show history with ASCII graph visualization
git log --graph --oneline --decorate
# Show all branches in graph format
git log --graph --oneline --all
# Show detailed changes (patch) for each commit
git log -p
# Show statistics about changes in each commit
git log --stat
# Show short statistics
git log --shortstat
# Limit number of commits shown
git log -n 5
# Show commits by specific author
git log --author="username"
# Show commits by multiple authors
git log --author="user1\|user2"
# Show commits in a date range
git log --since="2024-01-01" --until="2024-12-31"
# Show commits from last week
git log --since="1 week ago"
# Show commits that modified a specific file
git log -- filename
# Show commits with specific text in message
git log --grep="bug fix"
# Show commits that added or removed a specific string
git log -S "function_name"
# Show commits in reverse chronological order
git log --reverse
# Pretty format with custom output
git log --pretty=format:"%h - %an, %ar : %s"
# Show merge commits only
git log --merges
# Show non-merge commits only
git log --no-merges
Investigating Changes #
When you need to understand when and why a specific change was made, or who authored particular lines of code, these investigation commands become invaluable.
# Show who last modified each line of a file
git blame filename
# Show blame with line numbers
git blame -L 10,20 filename
# Show blame ignoring whitespace changes
git blame -w filename
# Find commits that introduced specific text
git log -S "search-string"
# Find commits that match a pattern
git log -G "regex-pattern"
# Show history of a specific line range
git log -L 10,20:filename
# View reflog (history of HEAD changes)
git reflog
# View reflog for a specific branch
git reflog show branch-name
# Show what changed in a specific commit
git show commit-hash
# Show files changed in a commit
git show --name-only commit-hash
# Compare two commits
git diff commit1 commit2
# Search through commit contents
git rev-list --all | xargs git grep "search-term"
Merging and Rebasing #
Integrating changes from different branches is a core part of collaborative development. Understanding when to merge versus rebase is crucial for maintaining a clean and understandable project history.
Merge Operations #
Merging combines changes from different branches, creating a merge commit that preserves the history of both branches. This is ideal when you want to maintain a complete record of all parallel development work.
# Merge a branch into current branch
git merge branch-name
# Merge without creating a merge commit (fast-forward only)
git merge --ff-only branch-name
# Always create a merge commit, even if fast-forward is possible
git merge --no-ff branch-name
# Merge with a custom commit message
git merge branch-name -m "Merge message"
# Merge but don't commit automatically
git merge --no-commit branch-name
# Abort an in-progress merge
git merge --abort
# Continue merge after resolving conflicts
git merge --continue
# Use a specific merge strategy
git merge -s recursive -X theirs branch-name
# Show merge conflicts
git diff --name-only --diff-filter=U
# Accept all changes from merged branch (theirs)
git checkout --theirs filename
# Accept all changes from current branch (ours)
git checkout --ours filename
Rebase Operations #
Rebasing rewrites commit history by moving commits to a new base, creating a linear history. This is particularly useful for keeping feature branches up to date with the main branch and creating clean, easy-to-follow project histories.
# Rebase current branch onto another branch
git rebase branch-name
# Rebase onto remote branch
git rebase origin/main
# Interactive rebase for last N commits
git rebase -i HEAD~3
# Interactive rebase from a specific commit
git rebase -i commit-hash
# Continue rebase after resolving conflicts
git rebase --continue
# Skip current commit during rebase
git rebase --skip
# Abort rebase and return to original state
git rebase --abort
# Preserve merge commits during rebase
git rebase -p branch-name
# Rebase onto a different branch
git rebase --onto new-base old-base branch-name
Advanced Operations #
These advanced commands provide powerful capabilities for managing your work, tagging releases, and manipulating repository history when necessary.
Stashing Changes #
Stashing allows you to temporarily save uncommitted changes without creating a commit, which is invaluable when you need to quickly switch contexts or pull updates.
# Stash current changes
git stash
# Stash with a descriptive message
git stash save "Work in progress on feature X"
# Stash including untracked files
git stash -u
# Stash including untracked and ignored files
git stash -a
# List all stashes
git stash list
# Show changes in most recent stash
git stash show
# Show detailed patch of stash
git stash show -p
# Apply most recent stash
git stash apply
# Apply most recent stash and remove it from stash list
git stash pop
# Apply a specific stash
git stash apply stash@{2}
# Pop a specific stash
git stash pop stash@{1}
# Create a new branch from stash
git stash branch branch-name stash@{0}
# Remove a specific stash
git stash drop stash@{0}
# Clear all stashes
git stash clear
Tags #
Tags are used to mark specific points in history as important, typically for releases. They provide a convenient way to reference specific commits with meaningful names.
# Create a lightweight tag
git tag v1.0.0
# Create an annotated tag with message
git tag -a v1.0.0 -m "Release version 1.0.0"
# Tag a specific commit
git tag -a v1.0.0 commit-hash -m "Retroactive tag"
# List all tags
git tag
# List tags matching a pattern
git tag -l "v1.*"
# Show tag information
git show v1.0.0
# Push a specific tag to remote
git push origin v1.0.0
# Push all tags to remote
git push origin --tags
# Delete a local tag
git tag -d v1.0.0
# Delete a remote tag
git push origin --delete v1.0.0
# Checkout a specific tag
git checkout v1.0.0
# Create a branch from a tag
git checkout -b branch-name v1.0.0
Reset and Restore #
Reset and restore commands allow you to undo changes at various levels, from unstaging files to completely resetting your branch to a previous state.
# Unstage a file (keep changes in working directory)
git restore --staged filename
# Unstage all files
git restore --staged .
# Discard changes in working directory for a file
git restore filename
# Discard all changes in working directory
git restore .
# Restore file from a specific commit
git restore --source=commit-hash filename
# Soft reset: move HEAD, keep changes staged
git reset --soft commit-hash
# Mixed reset (default): move HEAD, unstage changes
git reset commit-hash
# Hard reset: move HEAD, discard all changes
git reset --hard commit-hash
# Reset to remote branch state
git reset --hard origin/branch-name
# Reset single file to HEAD
git reset HEAD filename
# Undo last commit but keep changes
git reset --soft HEAD~1
# Undo last N commits
git reset --soft HEAD~3
Cherry-picking #
Cherry-picking allows you to apply specific commits from one branch to another, which is useful when you need only certain changes without merging entire branches.
# Apply a specific commit to current branch
git cherry-pick commit-hash
# Cherry-pick multiple commits
git cherry-pick commit1 commit2 commit3
# Cherry-pick a range of commits
git cherry-pick commit1^..commit2
# Cherry-pick without committing
git cherry-pick -n commit-hash
# Cherry-pick and edit commit message
git cherry-pick -e commit-hash
# Continue after resolving conflicts
git cherry-pick --continue
# Skip current commit
git cherry-pick --skip
# Abort cherry-pick operation
git cherry-pick --abort
# Cherry-pick from another branch
git cherry-pick branch-name~2
Maintenance and Cleanup #
Regular repository maintenance helps keep your Git repository efficient and healthy. These commands help you clean up unnecessary files and optimize repository performance.
Repository Maintenance #
Performing regular maintenance ensures your repository stays fast and doesn’t accumulate unnecessary data over time.
# Check repository integrity
git fsck
# Check with full verification
git fsck --full
# Cleanup unnecessary files and optimize repository
git gc
# Aggressive garbage collection (slower but more thorough)
git gc --aggressive
# Prune all unreachable objects
git prune
# Prune objects older than specified date
git prune --expire="30 days ago"
# Show what clean would remove (dry run)
git clean -n
# Remove untracked files
git clean -f
# Remove untracked files and directories
git clean -fd
# Remove ignored files as well
git clean -fdx
# Interactive clean
git clean -i
# Verify pack files
git verify-pack -v .git/objects/pack/*.idx
# Count objects in repository
git count-objects -v
# Optimize repository for better performance
git repack -ad
# Repack with maximum compression
git repack -a -d -f --depth=250 --window=250
Finding and Fixing Issues #
When things go wrong or you need to recover lost work, these commands help you diagnose and fix repository issues.
# Find broken or dangling references
git fsck --full
# Recover deleted files
git fsck --lost-found
# Show all unreachable commits
git fsck --unreachable
# View complete reflog history
git reflog expire --expire=now --all
# Force immediate garbage collection
git gc --prune=now
# Repair repository
git fsck --full && git gc --aggressive
# Find large files in history
git rev-list --objects --all | git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' | grep '^blob' | sort -k3 -n -r | head -20
# Remove file from all history (use with caution)
git filter-branch --tree-filter 'rm -f filename' HEAD
# Remove file using filter-repo (modern approach)
git filter-repo --path filename --invert-paths
# Verify all objects are accessible
git fsck --strict
# Check for corrupted objects
git hash-object --stdin < /dev/null
Essential Git Workflows and Best Practices #
Beyond individual commands, understanding common workflows and best practices will help you use Git more effectively in real-world development scenarios.
Feature Branch Workflow #
# Start a new feature
git checkout -b feature/new-feature main
# ... make changes ...
git add .
git commit -m "Implement new feature"
git push -u origin feature/new-feature
# Update feature branch with latest main
git checkout main
git pull origin main
git checkout feature/new-feature
git rebase main
git push --force-with-lease origin feature/new-feature
Hotfix Workflow #
# Create hotfix from production
git checkout -b hotfix/critical-bug main
# ... fix bug ...
git commit -am "Fix critical production bug"
git checkout main
git merge --no-ff hotfix/critical-bug
git tag -a v1.0.1 -m "Hotfix release"
git push origin main --tags
git branch -d hotfix/critical-bug
Best Practices Checklist #
- Always check status before committing: Use
git status
to verify what you’re about to commit - Write meaningful commit messages: Use imperative mood and explain why, not just what
- Commit early and often: Small, focused commits are easier to understand and revert if needed
- Use branches for all work: Never commit directly to main/master in team environments
- Keep main branch stable: Only merge tested, working code to main
- Pull before pushing: Always sync with remote before pushing to avoid conflicts
- Use .gitignore properly: Exclude generated files, dependencies, and sensitive data
- Review before committing: Use
git diff
to review changes before staging - Prune old branches regularly: Delete merged feature branches to keep repository clean
- Use SSH keys: Set up SSH authentication for secure, passwordless access
- Sign your commits: Use GPG signing for verified commits in professional projects
- Never rewrite public history: Avoid force pushing to shared branches
- Back up important work: Push to remote frequently or use additional backup strategies
- Learn to read logs: Understanding
git log
output helps you track project evolution - Use tags for releases: Mark significant versions with annotated tags
Common Troubleshooting Scenarios #
# Undo accidental commit to wrong branch
git reset --soft HEAD~1
git stash
git checkout correct-branch
git stash pop
git add .
git commit -m "Your message"
# Recover from bad merge
git merge --abort # if merge is in progress
git reset --hard ORIG_HEAD # if merge is completed
# Fix detached HEAD state
git checkout branch-name # reattach to branch
# or create new branch from current position
git checkout -b new-branch-name
# Resolve "refusing to merge unrelated histories"
git pull origin branch-name --allow-unrelated-histories
# Clean up after force push gone wrong
git reflog # find the commit you want to restore
git reset --hard commit-hash
# Remove sensitive data accidentally committed
git filter-branch --force --index-filter \
'git rm --cached --ignore-unmatch path/to/sensitive/file' \
--prune-empty --tag-name-filter cat -- --all
Conclusion #
This comprehensive Git cheatsheet covers the essential commands and workflows that developers use daily, from basic operations to advanced techniques. Git’s power lies not just in individual commands, but in understanding how they work together to support effective version control and collaboration. As you become more comfortable with these commands, you’ll develop your own workflows and discover which commands best suit your development style.
Remember that this guide is a reference tool—you don’t need to memorize every command. Keep it handy for quick lookups, and over time, the most relevant commands for your workflow will become second nature. For detailed information about any command, you can always use git help <command>
or git <command> --help
to access the official documentation.
The key to mastering Git is consistent practice and understanding the underlying concepts of commits, branches, and history manipulation. Start with the basics, gradually incorporate more advanced commands as needed, and don’t be afraid to experiment in test repositories. With these tools at your disposal, you’re well-equipped to handle any version control scenario that comes your way.