Git Essentials: The Complete Developer’s Cheatsheet

git essentials the complete cheat sheet

 


Introduction: Why Every Developer Needs Git

In 2005, Linus Torvalds (creator of Linux) faced a crisis: his team of 15,000 developers suddenly lost access to their version control system. His solution? Build a better one in two weeks.

That system became Git—now used by over 100 million developers worldwide and powering 90% of all software projects.

Whether you’re a solo developer building your first website or joining a team at a Fortune 500 company, Git is non-negotiable. This guide will take you from zero to proficient with clear explanations and practical examples.


What is Git? Understanding the Basics

Git is a distributed version control system that tracks changes to your files over time. Think of it as a time machine for your code combined with an unlimited “undo” button.

The Three States of Git

Git operates on a three-layer architecture that you need to understand:

┌─────────────────────┐
│  Working Directory  │  ← Your files (where you edit)
└──────────┬──────────┘
           │ git add (stage changes)
           ↓
┌─────────────────────┐
│   Staging Area      │  ← Changes ready to commit
└──────────┬──────────┘
           │ git commit (save permanently)
           ↓
┌─────────────────────┐
│    Repository       │  ← Permanent history
└─────────────────────┘
🎯 Real-world analogy: Taking a group photo
  1. Working Directory: Everyone positioning themselves
  2. Staging Area: Framing the shot (deciding who’s in it)
  3. Repository: The photo album (permanent record)

Getting Started: Installation and Setup

Installation

macOS:

brew install git

Ubuntu/Debian:

sudo apt-get install git

Windows:
Download from git-scm.com

First-Time Configuration

Set your identity (required before making commits):

# Set your name
git config --global user.name "Your Name"

# Set your email
git config --global user.email "you@example.com"

# Set default editor
git config --global core.editor "code --wait"  # VS Code

# Verify settings
git config --list

Core Workflow: Your Daily Git Commands

1. Starting a Repository

Create a new repository:

# Navigate to your project folder
cd my-project

# Initialize Git
git init

# Verify creation
ls -la  # You'll see a .git folder

Clone an existing repository:

# Clone from GitHub/GitLab
git clone https://github.com/username/project.git

# Clone and rename folder
git clone https://github.com/username/project.git my-custom-name

2. The Basic Workflow (90% of Daily Usage)

# 1. Check current status
git status

# 2. Stage changes
git add filename.py          # Specific file
git add .                    # All files in current directory
git add src/                 # Entire directory

# 3. Commit with message
git commit -m "Add user authentication feature"

# 4. View history
git log --oneline

Complete Example:

# Create a new file
echo "# My Project" > README.md

# Check status
git status
# Output: Untracked files: README.md

# Stage the file
git add README.md

# Check status again
git status
# Output: Changes to be committed: new file: README.md

# Commit
git commit -m "Add project README"

# View history
git log --oneline
# Output: a3f8b2c Add project README

3. Making Changes

Typical development cycle:

# Edit files in your editor
# (make changes to app.py, styles.css, etc.)

# Check what changed
git status
# Shows: modified: app.py, modified: styles.css

# See specific changes
git diff

# Stage and commit
git add app.py styles.css
git commit -m "Update login page styling and validation"

# Quick commit for tracked files
git commit -am "Fix typo in header"  # Stages + commits

Understanding Commits

What Makes a Good Commit?

A commit is a snapshot of your project at a specific moment. Each commit contains:

  • SHA: Unique identifier (e.g., a3f8b2c)
  • Author: Who made the change
  • Date: When it happened
  • Message: What changed (you write this!)
  • Parent: Previous commit (forms a chain)
✅ Good commit messages:
git commit -m "Fix null pointer error in user login"
git commit -m "Add email validation to registration form"
git commit -m "Refactor database connection logic for better error handling"
❌ Bad commit messages:
git commit -m "fixed stuff"
git commit -m "changes"
git commit -m "update"

Format: [Action] [What] [Where/Why if needed]

Viewing Commit History

# Full details
git log

# Compact view (most useful)
git log --oneline

# Last 5 commits
git log --oneline -n 5

# Visual graph
git log --graph --oneline --all

# Show what changed in a commit
git show a3f8b2c

# Show latest commit
git show HEAD

Inspecting Changes: The Power of Git Diff

Understanding Diffs

# See unstaged changes
git diff

# See staged changes
git diff --staged

# Quick summary
git diff --stat

Reading a Diff

diff --git a/app.py b/app.py
--- a/app.py              # Old version
+++ b/app.py              # New version
@@ -15,6 +15,8 @@         # Line numbers

 def login(username, password):
-    if username == "admin":    # RED = deleted
+    if not username:           # GREEN = added
+        return False           # GREEN = added
     return authenticate(username, password)
Key symbols:
  • - = Line deleted (red in terminal)
  • + = Line added (green in terminal)
  • No prefix = Context (unchanged)

Branching: Working on Features Safely

What is a Branch?

A branch is a movable pointer to a commit. It lets you work on features without affecting the main code.

main:     A --- B --- C
                       \
feature:                D --- E

Branch Commands

# List all branches (* = current branch)
git branch

# Create new branch
git branch feature-login

# Create and switch to new branch
git checkout -b feature-login

# Switch between branches
git checkout main
git checkout feature-login

# Delete branch
git branch -d feature-login

Practical Branching Example:

# Start from main
git checkout main

# Create feature branch
git checkout -b add-dark-mode

# Make changes
echo "dark-theme.css" > dark-theme.css
git add dark-theme.css
git commit -m "Add dark mode CSS"

# Make more changes
# ... edit files ...
git commit -m "Add dark mode toggle button"

# Switch back to main (your changes disappear!)
git checkout main

# Switch to feature (changes reappear!)
git checkout add-dark-mode

# Merge into main when done
git checkout main
git merge add-dark-mode

# Clean up
git branch -d add-dark-mode

Working with Remote Repositories

Understanding Remotes

A remote is a version of your repository hosted elsewhere (GitHub, GitLab, etc.).

Your Computer  ←→  GitHub/GitLab
               push/pull

Remote Commands

# View remotes
git remote -v

# Add remote
git remote add origin https://github.com/username/project.git

# Download updates (don't merge)
git fetch

# Download and merge
git pull

# Upload your commits
git push

# First-time push of new branch
git push -u origin feature-branch

Complete Remote Workflow:

# Clone a project
git clone https://github.com/company/project.git
cd project

# Create feature branch
git checkout -b fix-bug-123

# Make changes
git add .
git commit -m "Fix bug in payment processing"

# Push to remote
git push -u origin fix-bug-123

# Open Pull Request on GitHub
# After review and approval, merge on GitHub

# Update local main
git checkout main
git pull

# Delete local feature branch
git branch -d fix-bug-123

Undoing Changes: Git’s Safety Net

Before Committing

# Unstage file (keep changes in working directory)
git restore --staged file.py

# Discard changes in working directory (CAREFUL!)
git restore file.py

# Discard all changes (DANGEROUS!)
git restore .

After Committing

# Change last commit message
git commit --amend -m "New message"

# Add forgotten file to last commit
git add forgotten-file.py
git commit --amend --no-edit

# Undo last commit (keep changes)
git reset HEAD~1

# Undo last commit (discard changes - DANGEROUS!)
git reset --hard HEAD~1
⚠️ Warning: Commands with --hard flag permanently delete changes. Use with caution!

Practical Undo Example:

# Scenario: Accidentally committed sensitive data
git log --oneline
# a3f8b2c Add API keys (OOPS!)
# b4c5d6e Update config

# Undo the commit
git reset HEAD~1

# Remove sensitive file
rm config/api-keys.json

# Add to .gitignore
echo "config/api-keys.json" >> .gitignore

# Commit properly
git add .gitignore
git commit -m "Update gitignore to exclude API keys"

Essential Git Commands Cheatsheet

CommandDescription
git statusCheck current status
git add .Stage all changes
git commit -m "message"Save snapshot with message
git pushUpload commits to remote
git pullDownload and merge updates
git checkout -b featureCreate and switch to branch
git merge featureMerge branch into current
git log --onelineView commit history
git diffShow changes
git restore file.pyDiscard file changes

Common Workflows

Workflow 1: Solo Developer

# Daily work
git status
git add .
git commit -m "Add new feature"
git push

# Experiment safely
git checkout -b experiment
# ... make wild changes ...
# Hate it? → git checkout main (changes gone!)
# Love it? → git merge experiment

Workflow 2: Team Collaboration

# Start of day
git checkout main
git pull

# Create feature
git checkout -b feature-search
# ... work ...
git commit -m "Add search functionality"
git push -u origin feature-search

# Open Pull Request on GitHub
# Team reviews, you make changes
git commit -m "Address review feedback"
git push

# After merge
git checkout main
git pull
git branch -d feature-search

Workflow 3: Contributing to Open Source

# Fork project on GitHub, then:
git clone https://github.com/YOUR-USERNAME/project.git
cd project

# Add upstream remote
git remote add upstream https://github.com/ORIGINAL/project.git

# Create feature branch
git checkout -b fix-bug

# Make changes
git commit -m "Fix button alignment issue"

# Keep up to date
git fetch upstream
git rebase upstream/main

# Push to your fork
git push origin fix-bug

# Open Pull Request from your fork to original

.gitignore: What NOT to Track

Creating .gitignore

# Create the file
touch .gitignore

Common Python .gitignore

# Python
__pycache__/
*.py[cod]
*.pyc
*.pyo
*.pyd
.Python
env/
venv/
ENV/
*.egg-info/
dist/
build/

# IDEs
.vscode/
.idea/
*.swp

# OS files
.DS_Store
Thumbs.db

# Environment variables
.env
secrets.json

# Logs
*.log

Common JavaScript/Node .gitignore

# Dependencies
node_modules/
npm-debug.log
yarn-error.log

# Build
dist/
build/
.cache/

# Environment
.env
.env.local

# IDEs
.vscode/
.idea/

# OS
.DS_Store
Check what’s ignored:
git status --ignored
git check-ignore -v file.py  # Why is this ignored?

Git Best Practices

1. Commit Often, Commit Early

✅ Good: Small, focused commits
git commit -m "Add user model"
git commit -m "Add user validation"
git commit -m "Add user tests"
❌ Bad: One huge commit
git commit -m "Add entire user system"

2. Write Meaningful Commit Messages

Use this format:

[Type]: [Brief description]

[Optional detailed explanation]
[Optional references to issues]

Example:

git commit -m "Fix: Resolve null pointer in login handler

- Added validation for empty username
- Added test case for null input
- Fixes #123"

3. Pull Before Push

# Always get latest changes first
git pull
# Resolve any conflicts
git push

4. Branch for Features

# Keep main stable
git checkout main
git checkout -b new-feature
# Work on feature
# When done, merge back

5. Review Before Committing

# Always check what you're committing
git status
git diff
git add .
git diff --staged  # Review staged changes
git commit -m "message"

6. Never Commit Sensitive Data

❌ DON’T commit:
  • API keys
  • Passwords
  • Database credentials
  • Private keys
  • .env files
✅ DO use:
  • .gitignore
  • Environment variables
  • Secret management tools

Troubleshooting Common Issues

Issue 1: Merge Conflicts

What you’ll see:

<<<<<<< HEAD
your changes
=======
their changes
>>>>>>> branch-name

How to resolve:

# 1. Open the file
# 2. Choose which version to keep (or combine them)
# 3. Remove conflict markers (<<<, ===, >>>)
# 4. Save file

# 5. Stage and commit
git add resolved-file.py
git commit -m "Resolve merge conflict"

Issue 2: Accidentally Committed Wrong Files

# Undo commit, keep changes
git reset HEAD~1

# Remove file from staging
git restore --staged unwanted-file.py

# Commit properly
git add correct-files.py
git commit -m "Add correct files"

Issue 3: Need to Switch Branches with Uncommitted Changes

# Save changes temporarily
git stash

# Switch branches
git checkout other-branch
# ... do work ...

# Return and restore changes
git checkout original-branch
git stash pop

Issue 4: Pushed Sensitive Data

⚠️ Important: DON’T just delete and commit again! The data is still in history.

Option 1: Use git-filter-repo (recommended)

pip install git-filter-repo
git filter-repo --path secrets.json --invert-paths

Option 2: Contact GitHub support – They can purge sensitive data from history

Then: Force push (CAREFUL!)

git push --force

Advanced Tips for Productivity

Useful Aliases

Add to ~/.gitconfig:

[alias]
    # Shortcuts
    st = status -sb
    co = checkout
    br = branch
    cm = commit -m
    
    # Better logging
    lg = log --oneline --graph --decorate --all
    last = log -1 HEAD --stat
    
    # Diffs
    d = diff
    ds = diff --staged
    
    # History
    hist = log --pretty=format:'%C(yellow)%h%Creset %C(green)%ad%Creset | %s%C(cyan)%d%Creset %C(blue)[%an]%Creset' --graph --date=short

Usage:

git st      # Instead of git status
git lg      # Beautiful log
git last    # Show last commit

Git Stash for Context Switching

# Save work temporarily
git stash save "WIP: working on login"

# Switch contexts
git checkout other-branch
# ... work ...

# Return
git checkout original-branch
git stash list
git stash pop  # Restore and delete stash

Finding Bugs with Git Bisect

# Something broke, but you don't know when
git bisect start
git bisect bad                    # Current version broken
git bisect good v1.0             # This version worked

# Git checks out middle commit
# Test it manually or run: npm test

git bisect good   # If works
git bisect bad    # If broken

# Repeat until Git identifies the culprit
git bisect reset  # Done

Resources and Next Steps

Learning Resources

Interactive Learning:

Documentation:

Cheatsheets:

Help with Mistakes:

Recommended Tools

GUI Clients:

  • GitHub Desktop – Simple, beginner-friendly
  • GitKraken – Beautiful visualization
  • Sourcetree – Feature-rich, free

IDE Integration:

  • VS Code (built-in Git support)
  • IntelliJ IDEA (excellent Git tools)
  • Sublime Merge (fast and powerful)

What to Learn Next

After mastering the basics:

  1. Git Rebase – Rewrite history cleanly
  2. Cherry-pick – Copy specific commits
  3. Submodules – Manage dependencies
  4. Git Hooks – Automate workflows
  5. Advanced merging strategies

⚡ Quick Reference Card

# Essential Commands
git status                    # Check status
git add .                     # Stage all
git commit -m "message"       # Save snapshot
git push                      # Upload
git pull                      # Download

# Branching
git checkout -b feature       # Create + switch
git checkout main             # Switch branch
git merge feature             # Merge

# History
git log --oneline            # View commits
git diff                     # See changes
git show HEAD                # Latest commit

# Undo
git restore file.py          # Discard changes
git reset HEAD~1             # Undo commit

# Emergency
git reflog                   # Full history
git stash                    # Save work temporarily

📥 Download Free PDF Cheatsheet

🎁 Get Your Free Git Essentials PDF!

Download our comprehensive Git Essentials Cheatsheet – a beautifully designed, printer-friendly reference guide perfect for your desk or digital library!

📄 2-Page PDF • Color-coded sections

🎨 Professional Design • Ready to print

⚡ Quick Reference • 8 essential sections

✅ All Commands • From beginner to advanced

📥 Download Free PDF Cheatsheet

No email required • Instant download • Free forever

📋 What’s Inside the PDF:

  • Installation & Setup – Get Git running on any platform
  • Essential Daily Commands – The 90% you’ll use every day
  • Repository Operations – Init, clone, and remotes
  • Branching & Merging – Master feature workflows
  • Undoing Changes – Fix mistakes with confidence
  • Viewing History – Navigate your project timeline
  • Git Stash – Save work without committing
  • Best Practices – Professional tips and tricks

“This cheatsheet has been a game-changer for our development team. We printed copies for everyone’s desk!”

— Sarah K., Senior Developer


Conclusion: Why Git Matters

Git has transformed software development from a solo activity into a global collaboration platform. It powers:

  • Every app on your phone
  • Every website you visit
  • Every cloud service you use
  • 100+ million developers worldwide
  • 330+ million repositories on GitHub

Whether you’re building your first website, contributing to open source, or joining a development team, Git is your foundation.

Start simple:
  • git status (check what changed)
  • git add (prepare changes)
  • git commit (save snapshot)
  • git push (share with world)

Master these four commands, and you’re 80% of the way there.

The best way to learn Git is to use it. Start a project today, make mistakes, experiment with branches, and don’t be afraid to mess up—that’s what version control is for!

🚀 Ready to Master Git?

Start your journey today with our interactive Git tutorial!

Get Started Now

Happy coding! Remember: Git is your safety net. Commit early, commit often, and never fear breaking things—you can always go back in time! 🚀


Have questions or suggestions? Leave a comment below!

Found this helpful? Share it with fellow developers!

* Paste the CSS from the


Discover more from Enriktech.com

Subscribe to get the latest posts sent to your email.

Scroll to Top