Ultimate Git Cheatsheet: From Beginner to Advanced
The Complete Guide to Version Control with Git
Git is the most widely-used version control system that helps developers track changes, collaborate effectively, and maintain code quality. This comprehensive cheatsheet provides everything you need to master Git - from basic commands to advanced techniques.
Why Use Git?
- History Tracking: Keep a complete history of all changes made to your codebase
- Collaboration: Work seamlessly with team members without overwriting each other's work
- Branching: Create separate environments for developing new features without affecting the main codebase
- Backup: Store your code securely on remote repositories
- Experimentation: Try new ideas without risking your stable code
- Accountability: Always know who made what changes and when
Let's start with the essential commands every developer should know!
Basic Git Commands for Beginners 🚀
Every Git journey starts with these fundamental commands. Master these basics and you'll be well on your way to effective version control!
Initialize a Repository
Bash1# Create a new Git repository in your current directory
2git init
What it does: Transforms your current directory into a Git repository by creating a hidden .git folder that stores all version history.
When to use it: When starting a new project or wanting to track an existing project with Git.
Check Status
Bash1# View the status of your working directory
2git status
3
4# Short status format (more concise output)
5git status -s
What it does: Shows which files have been changed, which are staged for commit, and which aren't being tracked by Git.
Pro tip: Run this command frequently! It's your best friend for understanding the current state of your repository.
Stage Changes
Bash1# Add a specific file to the staging area
2git add filename.txt
3
4# Add multiple files
5git add file1.txt file2.txt
6
7# Add all files in the current directory
8git add .
9
10# Add all files of a specific type (e.g., all JavaScript files)
11git add *.js
What it does: Prepares your changes to be committed by moving them to the "staging area" (think of it as a loading dock before shipping).
Why it matters: This two-step process (stage then commit) gives you fine control over exactly which changes go into each commit.
Commit Changes
Bash1# Commit staged changes with a message
2git commit -m "Your commit message here"
3
4# Add changes and commit in one command (only works for modified files, not new files)
5git commit -am "Add and commit message"
What it does: Creates a permanent snapshot of your staged changes in the Git history.
Best practice: Write clear, descriptive commit messages that explain why the change was made, not just what was changed. Follow the convention of using present tense: "Add login feature" instead of "Added login feature".
Push/Pull
Bash1# Push your local commits to the remote repository
2git push origin main
3
4# Download changes from the remote repository and merge them into your local branch
5git pull origin main
6
7# Fetch changes without automatically merging
8git fetch origin
Push: Uploads your commits to the remote repository so others can see your changes.
Pull: Downloads changes from the remote repository and integrates them into your local branch.
Fetch vs. Pull: fetch just downloads the changes without merging them, giving you a chance to review before integrating with merge. pull is essentially fetch + merge in one command.
Branching and Merging: The Power of Parallel Development 🌿
Branching is one of Git's most powerful features, allowing teams to work on multiple features simultaneously without interference.
Branches
Bash1# List all branches (* indicates current branch)
2git branch
3
4# List remote branches
5git branch -r
6
7# List both local and remote branches
8git branch -a
9
10# Create a new branch (but stay on current branch)
11git branch branch-name
12
13# Create and switch to a new branch (most common approach)
14git checkout -b branch-name
15
16# Switch to an existing branch
17git checkout branch-name
18
19# Switch to the previous branch you were on
20git checkout -
What are branches?: Think of branches as separate versions or timelines of your project. The main branch (often called main or master) usually contains the stable version, while feature branches are used to develop new functionality without disturbing the main codebase.
Branch naming conventions: Use descriptive names like feature/login-system, bugfix/header-alignment, or refactor/database-queries.
Merging
Bash1# Merge a branch into your current branch
2git merge branch-name
3
4# Merge with a custom commit message
5git merge branch-name -m "Merge message"
6
7# Abort a merge if you encounter conflicts and want to start over
8git merge --abort
What it does: Combines changes from one branch into another, typically to incorporate completed features into the main codebase.
Merge workflow:
- Finish your work on a feature branch
- Switch to the receiving branch (e.g.,
git checkout main) - Merge the feature branch (
git merge feature-branch) - Resolve any conflicts if they occur
- Push the updated main branch to the remote repository
When you might encounter conflicts: When the same part of a file has been changed differently in both branches. Don't panic! Git will mark the conflicts and ask you to resolve them manually.
Delete Branches
Bash1# Delete a local branch
2git branch -d branch-name
3
4# Force delete a local branch
5git branch -D branch-name
6
7# Delete a remote branch
8git push origin --delete branch-name
Commit History: Understanding Your Project Timeline 📜
The ability to see the complete history of changes is one of Git's most valuable features, especially for debugging and understanding project evolution.
View Logs
Bash1# View commit history
2git log
3
4# View condensed log (one line per commit)
5git log --oneline
6
7# View log with graph visualization (great for understanding branch structure)
8git log --graph --oneline --decorate
9
10# View log for a specific file
11git log filename.txt
12
13# View changes made in each commit (shows actual code changes)
14git log -p
15
16# View stats for each commit (how many lines changed in each file)
17git log --stat
When to use it: When you need to understand the project's history, see who made what changes, or find when a specific change was introduced.
Pro tip: Add the --author="username" flag to filter commits by a specific person, or use --since="2 weeks ago" to limit the time range.
Comparing Changes
Bash1# Compare working directory with staging area
2git diff
3
4# Compare staging area with last commit
5git diff --staged
6
7# Compare two branches
8git diff branch1 branch2
9
10# Compare two commits
11git diff commit1 commit2
12
13# Compare a file between two commits
14git diff commit1 commit2 -- filename
Advanced Git Commands: Level Up Your Version Control Skills 🔥
These more sophisticated commands help you handle complex scenarios and give you greater control over your Git workflow.
Stashing Changes: The Temporary Drawer
Bash1# Temporarily save uncommitted changes and revert to a clean working directory
2git stash
3
4# Save stash with a descriptive message
5git stash save "Work in progress on login feature"
6
7# List all your saved stashes
8git stash list
9
10# Apply most recent stash without removing it from the stash list
11git stash apply
12
13# Apply a specific stash by its index
14git stash apply stash@{2}
15
16# Apply and remove most recent stash (common usage)
17git stash pop
18
19# Remove a specific stash without applying it
20git stash drop stash@{1}
21
22# Remove all stashed changes
23git stash clear
What is stashing?: Think of it as a clipboard or drawer where you can temporarily store changes you're not ready to commit.
When to use it:
- When you need to switch branches but aren't ready to commit your changes
- When you want to try an alternate approach without losing your current work
- When you need to pull changes but have uncommitted local modifications
Rebasing
Bash1# Rebase current branch onto another branch
2git rebase main
3
4# Interactive rebase for more control
5git rebase -i HEAD~3 # Rebase last 3 commits
6
7# Continue a rebase after resolving conflicts
8git rebase --continue
9
10# Abort a rebase
11git rebase --abort
Resetting
Bash1# Unstage a file (keep changes in working dir)
2git reset filename.txt
3
4# Unstage all files
5git reset
6
7# Reset to a previous commit (keep changes)
8git reset commit-hash
9
10# Reset to a previous commit (discard changes)
11git reset --hard commit-hash
12
13# Reset to remote branch state
14git reset --hard origin/main
Remote Repositories: Collaborating with the World 🌐
Remote repositories are versions of your project hosted on the internet or a network, enabling collaboration with others.
Manage Remotes
Bash1# View all remote repositories and their URLs
2git remote -v
3
4# Add a remote repository
5git remote add origin https://github.com/username/repo.git
6
7# Change the URL of an existing remote
8git remote set-url origin https://github.com/username/repo.git
9
10# Remove a remote repository connection
11git remote remove origin
What are remotes?: Remote repositories are copies of your Git repository hosted elsewhere - typically on platforms like GitHub, GitLab, or Bitbucket. The standard name for the primary remote is "origin".
Why use remotes?: They allow for:
- Backup of your code
- Collaboration with other developers
- Continuous integration/deployment workflows
- Code reviews via pull/merge requests
Clone Repository
Bash1# Clone a repository
2git clone https://github.com/username/repo.git
3
4# Clone to a specific directory
5git clone https://github.com/username/repo.git my-directory
6
7# Clone a specific branch
8git clone -b branch-name https://github.com/username/repo.git
Fetch and Pull
Bash1# Fetch from all remotes
2git fetch --all
3
4# Fetch a specific remote
5git fetch origin
6
7# Pull with rebase instead of merge
8git pull --rebase origin main
Configuration: Setting Up Git for Success ⚙️
Properly configuring Git is essential for effective collaboration and maintaining a clean commit history.
User Information
Bash1# Set global username (used for all repositories unless overridden)
2git config --global user.name "Your Name"
3
4# Set global email address
5git config --global user.email "your.email@example.com"
6
7# Set username for a specific repository only
8git config user.name "Your Name"
Why it matters: Your name and email will be attached to every commit you make, helping others identify who made which changes.
Best practice: Use the same email address that you use for your GitHub/GitLab/Bitbucket account to ensure proper attribution.
View Configuration
Bash1# View all configurations
2git config --list
3
4# View global configurations
5git config --global --list
6
7# View specific setting
8git config user.name
Default Editor
Bash1# Set default editor
2git config --global core.editor "code --wait" # VS Code
3git config --global core.editor "vim" # Vim
4git config --global core.editor "nano" # Nano
Useful Git Tips: Save Time and Avoid Common Mistakes ⚡
These shortcuts and techniques will make your Git workflow smoother and help you recover from mistakes.
Undoing Changes: Everyone Makes Mistakes
Bash1# Discard changes to a file (restore it to the last committed state)
2git checkout -- filename.txt
3
4# Discard all changes in working directory (dangerous - you'll lose all uncommitted work!)
5git checkout -- .
6
7# Safely undo a commit by creating a new commit that reverses the changes
8git revert commit-hash
9
10# Fix the last commit message
11git commit --amend -m "New commit message"
12
13# Add forgotten files to the last commit without changing the commit message
14git add forgotten-file.txt
15git commit --amend --no-edit
Safety tip: Before using destructive commands like checkout -- . or reset --hard, consider making a backup with git stash so you can recover if needed.
When to use revert vs. reset: Use revert when the commit has already been pushed to a shared repository. Use reset only for local changes that haven't been shared.
Tagging
Bash1# List all tags
2git tag
3
4# Create a lightweight tag
5git tag v1.0.0
6
7# Create an annotated tag
8git tag -a v1.0.0 -m "Release version 1.0.0"
9
10# Tag a specific commit
11git tag -a v0.9.0 commit-hash -m "Tag message"
12
13# Push tags to remote
14git push origin --tags
15
16# Push a specific tag
17git push origin v1.0.0
18
19# Delete a local tag
20git tag -d v1.0.0
21
22# Delete a remote tag
23git push --delete origin v1.0.0
Ignoring Files: Keep Your Repository Clean
Bash1# Create a .gitignore file in your repository root
2touch .gitignore
Common .gitignore patterns:
Bash1# Ignore specific file
2filename.txt
3secrets.json
4.env
5
6# Ignore file extensions
7*.log
8*.tmp
9*.zip
10*.pdf
11
12# Ignore directories
13node_modules/ # NPM packages
14dist/ # Build output
15.vscode/ # Editor settings
16__pycache__/ # Python cache
17.idea/ # JetBrains IDEs
18
19# Ignore all files in a directory except specific ones
20logs/*
21!logs/.gitkeep # Keep the logs directory in Git but ignore its contents
What should you ignore?:
- Build artifacts and compiled code
- Dependencies that can be reinstalled (npm packages, pip packages)
- Environment-specific configuration files
- User-specific IDE settings
- Temporary files, logs, and caches
- Sensitive information (API keys, credentials, .env files)
Pro tip: Visit gitignore.io to generate comprehensive .gitignore files for your specific languages and tools.
Aliases
Bash1# Create a git alias
2git config --global alias.co checkout
3git config --global alias.br branch
4git config --global alias.ci commit
5git config --global alias.st status
6
7# Create a complex alias
8git config --global alias.logline "log --graph --oneline --decorate"
Cleaning
Bash1# Remove untracked files (dry run)
2git clean -n
3
4# Remove untracked files
5git clean -f
6
7# Remove untracked files and directories
8git clean -fd
9
10# Remove ignored files too
11git clean -fdx
Git Resources: Continue Your Learning Journey 📚
Documentation and Tutorials
- Official Git Documentation
- The comprehensive reference for all Git commands
- Pro Git Book
- Free, detailed book covering all aspects of Git
- GitHub Guides
- Practical tutorials for working with GitHub
- Atlassian Git Tutorials
- Well-explained guides with visualizations
Interactive Learning
- Learn Git Branching
- Visual, interactive way to learn Git branching
- GitHub Learning Lab
- Hands-on projects to build real-world skills
- Git-it
- Desktop app with challenges to learn Git
- Katacoda Git Scenarios
- Learn in your browser with guided scenarios
Cheat Sheets
- Git Cheat Sheet by GitHub
- Official GitHub reference
- Git Cheat Sheet by Atlassian
- Comprehensive guide
- Git Command Explorer
- Find the right commands by describing what you want to do
Git GUIs (Graphical User Interfaces)
- GitHub Desktop
- Simple, user-friendly interface for GitHub users
- GitKraken
- Powerful visual Git client with intuitive interface
- Sourcetree
- Free GUI by Atlassian with detailed visualizations
- Visual Studio Code Git Integration
- Built-in Git tools in popular code editor
Git Workflow Strategies
- Gitflow Workflow
- Advanced branching model for structured releases
- GitHub Flow
- Simplified, continuous delivery workflow
- Trunk Based Development
- Approach for teams practicing continuous integration
Git for Teams
- Git Team Workflows
- Strategies for effective collaboration
- Pull Request Best Practices
- Tips for effective code reviews