π― Table of Contents
- What is Git?
- Basic Concepts
- Setting Up Git
- Creating Your First Repository
- Basic Git Operations
- Working with Remote Repositories
- Comparing Changes
- Essential Day-to-Day Operations
- Common Workflows
- Daily Workflow Cheat Sheet
- Troubleshooting
- Quick Reference
π€ What is Git?
Git is a version control system – think of it as a time machine for your code!
Real-World Analogy
Imagine you’re writing a book:
- Without Git: You save “book_v1.docx”, “book_v2.docx”, “book_final.docx”, “book_final_final.docx” π
- With Git: You have one file, and Git remembers every change you made, when you made it, and why
Why Use Git?
β
Track Changes: See what changed and when
β
Collaborate: Multiple people can work on the same project
β
Backup: Your code is saved on GitHub (cloud)
β
Undo Mistakes: Go back to any previous version
β
Branching: Work on features without breaking main code
π Basic Concepts
Key Terms You Need to Know
| Term | Simple Explanation | Real-World Analogy |
|---|---|---|
| Repository (Repo) | A folder that Git tracks | Your project folder |
| Commit | A saved snapshot of your code | Taking a photo of your work |
| Branch | A separate line of development | A parallel universe for your code |
| Remote | A copy of your repo on the internet | Your code on GitHub |
| HEAD | Your current position in history | “You are here” marker |
| Staging | Preparing files to be saved | Putting items in a shopping cart |
The Three States of Files
Working Directory β Staging Area β Repository
(Your files) (Ready to save) (Saved!)
- Working Directory: Files you’re editing right now
- Staging Area: Files you’ve marked to save (like a shopping cart)
- Repository: Files that are permanently saved (committed)
βοΈ Setting Up Git
Step 1: Install Git
Windows:
- Download from:Β https://git-scm.com/download/win
- Run installer (use default options)
Mac:
# Open Terminal and run:
xcode-select --install
Linux (Ubuntu/Debian):
sudo apt update
sudo apt install git
Step 2: Configure Git (One-time setup)
# Tell Git who you are
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
# Check your settings
git config --list
Example:
git config --global user.name "John Doe"
git config --global user.email "john.doe@college.edu"
π Creating Your First Repository
Scenario: Starting a New Project
Let’s say you want to create a project called “my-website”.
Option 1: Start Fresh (Local First)
# Step 1: Create a folder
mkdir my-website
cd my-website
# Step 2: Initialize Git (this makes it a Git repository)
git init
# Step 3: Create your first file
echo "# My Website" > README.md
# Step 4: Check status
git status
What you’ll see:
On branch main
Untracked files:
README.md
Option 2: Clone from GitHub (Remote First)
# Step 1: Go to GitHub and create a new repository
# (Click "New repository" button)
# Step 2: Copy the repository URL
# Example: https://github.com/yourusername/my-website.git
# Step 3: Clone it to your computer
git clone https://github.com/yourusername/my-website.git
cd my-website
# Step 4: You're ready! The repo is already set up
π Basic Git Operations
1. git status – See What’s Changed
What it does: Shows you what files have changed
git status
Example Output:
On branch main
Changes not staged for commit:
modified: index.html
modified: style.css
Untracked files:
new-page.html
Translation:
index.htmlΒ andΒstyle.cssΒ were changed but not savednew-page.htmlΒ is a new file Git doesn’t know about yet
2. git add – Stage Files (Put in Shopping Cart)
What it does: Tells Git “I want to save these files”
# Add a specific file
git add index.html
# Add all changed files
git add .
# Add all files of a type
git add *.html
Example:
# You edited index.html and created about.html
git add index.html about.html
# Check status again
git status
# Now shows: "Changes to be committed"
Analogy: Like putting items in your shopping cart before checkout
3. git commit – Save Your Changes
What it does: Permanently saves your staged changes
# Commit with a message
git commit -m "Your message here"
Example:
git commit -m "Added homepage and about page"
Good Commit Messages: β
"Fixed login bug"
β
"Added user registration form"
β
"Updated CSS styling"
Bad Commit Messages: β "asdf"
β "changes"
β "fixed stuff"
Why? Good messages help you remember what you did later!
4. git log – View History
What it does: Shows you all your commits (history)
# Basic log
git log
# One line per commit (easier to read)
git log --oneline
# Show last 5 commits
git log -5 --oneline
# Pretty format with graph
git log --oneline --graph --all
Example Output:
commit abc1234 (HEAD -> main)
Author: John Doe <john@example.com>
Date: Mon Dec 25 10:30:00 2024
Added homepage and about page
commit def5678
Author: John Doe <john@example.com>
Date: Sun Dec 24 15:20:00 2024
Initial commit
Understanding:
abc1234Β = Unique commit ID (like a fingerprint)HEAD -> mainΒ = This is where you are now- Most recent commit is at the top
π Working with Remote Repositories
Understanding Local vs Remote
βββββββββββββββββββ βββββββββββββββββββ
β Your Computer β β GitHub β
β (Local Repo) β βββββββΊ β (Remote Repo) β
β β β β
β git push β βββββββΊ β β
β git pull β βββββββ β β
β git fetch β βββββββ β β
βββββββββββββββββββ βββββββββββββββββββ
1. git remote – Manage Remote Connections
What it does: Shows/manages your connection to GitHub
# See your remotes
git remote -v
# Add a remote (usually done once)
git remote add origin https://github.com/username/repo.git
# Change remote URL
git remote set-url origin https://github.com/username/new-repo.git
# Remove remote
git remote remove origin
Example:
git remote -v
# Output:
# origin https://github.com/johndoe/my-website.git (fetch)
# origin https://github.com/johndoe/my-website.git (push)
Translation: “origin” is the name for your GitHub repository
2. git fetch – Check What’s New (Without Changing Files)
What it does: Downloads information about changes on GitHub, but doesn’t change your files
git fetch origin
Analogy: Checking your mailbox for new letters (you see what’s there, but don’t open them yet)
Example:
# Your friend pushed changes to GitHub
git fetch origin
# Now you know there are new changes, but your files are unchanged
# You can compare before deciding to pull
When to use:
- You want to see what changed on GitHub
- You want to compare before updating
- You’re not ready to merge changes yet
3. git pull – Download and Merge Changes
What it does: Downloads changes from GitHub AND updates your local files
# Pull from remote
git pull origin main
# Or just (if you're on main branch)
git pull
What happens:
- Downloads new commits from GitHub
- Merges them into your local branch
- Updates your files
Example:
# Your friend added a new file on GitHub
git pull origin main
# Now you have that file on your computer too!
β οΈ Warning: Only pull when your working directory is clean (no uncommitted changes)
Check first:
git status
# If it says "working tree clean", you're safe to pull
4. git push – Upload Your Changes
What it does: Uploads your local commits to GitHub
# Push to remote
git push origin main
# Or just (if you're on main branch)
git push
Example:
# You made changes and committed them
git add .
git commit -m "Added contact page"
git push origin main
# Now your changes are on GitHub!
What happens:
- Git uploads your commits to GitHub
- Other people can now see your changes
- Your code is backed up in the cloud
β οΈ Common Error:
error: failed to push some refs
hint: Updates were rejected because the remote contains work...
Solution: Someone else pushed changes. Pull first, then push:
git pull origin main
git push origin main
π Comparing Changes
git diff – See What Changed
What it does: Shows you the exact differences between versions
# See changes in working directory (not staged)
git diff
# See changes that are staged
git diff --staged
# Compare your local with remote
git diff HEAD origin/main
# Compare two commits
git diff abc1234 def5678
# See what files changed (summary)
git diff --stat
Example:
# You edited a file but haven't committed
git diff index.html
Output:
- <h1>Old Title</h1>
+ <h1>New Title</h1>
- <p>Old content</p>
+ <p>New content here</p>
Reading the output:
- Lines starting withΒ
-Β = Removed (red) - Lines starting withΒ
+Β = Added (green) - Lines withoutΒ
-Β orΒ+Β = Context (unchanged)
Comparing Local vs Remote
# Step 1: Fetch to update your knowledge of remote
git fetch origin
# Step 2: See what commits are on remote but not local
git log HEAD..origin/main --oneline
# Step 3: See what files changed
git diff HEAD origin/main
# Step 4: See summary of changes
git diff --stat HEAD origin/main
Example Workflow:
# Check what's new on GitHub
git fetch origin
# See commit messages
git log HEAD..origin/main --oneline
# Output:
# abc1234 Added new feature
# def5678 Fixed bug
# See what files changed
git diff --stat HEAD origin/main
# Output:
# file1.py | 10 +++++-----
# file2.py | 5 +++++
# 2 files changed, 10 insertions(+), 5 deletions(-)
# Now decide: pull or not?
git pull origin main
π Common Workflows
Workflow 1: Starting a New Project
# 1. Create folder
mkdir my-project
cd my-project
# 2. Initialize Git
git init
# 3. Create files
echo "# My Project" > README.md
# ... create other files ...
# 4. Add all files
git add .
# 5. First commit
git commit -m "Initial commit"
# 6. Create repo on GitHub, then connect
git remote add origin https://github.com/username/my-project.git
# 7. Push to GitHub
git push -u origin main
Workflow 2: Daily Development
# Morning: Get latest changes
git pull origin main
# Work on your code...
# Edit files, create new files, etc.
# Check what changed
git status
# Stage your changes
git add .
# Commit
git commit -m "Added new feature"
# Push to GitHub
git push origin main
Workflow 3: Collaborating with Others
# Before starting work: Always pull first!
git pull origin main
# Do your work...
git add .
git commit -m "My changes"
# Before pushing: Pull again (in case someone else pushed)
git pull origin main
# Resolve any conflicts if needed, then push
git push origin main
Workflow 4: Safe Comparison Before Pulling
# Step 1: See what's on GitHub (doesn't change your files)
git fetch origin
# Step 2: Compare
git log HEAD..origin/main --oneline
git diff HEAD origin/main
# Step 3: If you like the changes, pull
git pull origin main
# If you don't like them, your files stay unchanged
π― Daily Workflow Cheat Sheet
Morning Routine
git pull origin main # Get latest changes
git status # Check your status
Making Changes
# Edit files...
git status # See what changed
git add . # Stage changes
git commit -m "message" # Save changes
git push origin main # Upload to GitHub
Switching Tasks
git stash # Save current work
git checkout other-branch # Switch branch
# Do other work...
git checkout original-branch
git stash pop # Get work back
Undoing Mistakes
# Undo file changes (not committed)
git restore file.txt
# Undo staging
git restore --staged file.txt
# Undo last commit (keep changes)
git reset HEAD~1
# Undo last commit safely (for shared branches)
git revert HEAD
Cleaning Up
# Remove untracked files
git clean -n # Preview first!
git clean -f # Then remove
# Delete merged branch
git branch -d old-branch
π οΈ Troubleshooting
Problem: “Your branch is behind ‘origin/main'”
Meaning: GitHub has commits you don’t have locally
Solution:
git pull origin main
Problem: “Your branch is ahead of ‘origin/main'”
Meaning: You have local commits not on GitHub
Solution:
git push origin main
Problem: “Please commit your changes or stash them”
Meaning: You have uncommitted changes
Options:
# Option 1: Commit them
git add .
git commit -m "My changes"
git pull origin main
# Option 2: Stash them (save for later)
git stash
git pull origin main
git stash pop # Get your changes back
Problem: Merge Conflicts
What it means: Git can’t automatically merge changes
Solution:
# Git will mark conflicts in files
# Look for markers like:
<<<<<<< HEAD
Your code
=======
Their code
>>>>>>> origin/main
# Edit the file to resolve, then:
git add conflicted-file.py
git commit -m "Resolved merge conflict"
Problem: “Cannot pull because you have uncommitted changes”
Solution:
# Option 1: Stash your changes
git stash
git pull origin main
git stash pop
# Option 2: Commit your changes first
git add .
git commit -m "My changes"
git pull origin main
Problem: “Accidentally deleted a branch”
Solution:
# Use reflog to find it
git reflog
# Find the commit hash before deletion
git checkout <commit-hash>
git branch recovered-branch
Problem: “Want to undo last commit but keep changes”
Solution:
# Soft reset (keeps changes staged)
git reset --soft HEAD~1
# Mixed reset (keeps changes, unstages them)
git reset HEAD~1
# Then edit and recommit
git commit -m "Corrected commit"
Problem: “Pushed wrong commit to GitHub”
Solution:
# If it's the last commit and no one else pulled:
git reset HEAD~1
# Edit files
git add .
git commit -m "Corrected commit"
git push --force origin main # β οΈ Only if safe!
# If others might have pulled, use revert instead:
git revert HEAD
git push origin main
π§ Essential Day-to-Day Operations
1. git stash – Save Changes Temporarily
What it does: Temporarily saves your uncommitted changes so you can switch branches or pull
When to use:
- You’re working on something but need to switch branches
- You need to pull but have uncommitted changes
- You want to test something without committing
# Save your changes
git stash
# See your stashes
git stash list
# Get your changes back
git stash pop # Applies and removes the stash
git stash apply # Applies but keeps the stash
# Delete a stash
git stash drop
# Clear all stashes
git stash clear
Example:
# You're working on a feature, but need to fix a bug
git stash # Save your work
git checkout main # Switch to main branch
# Fix the bug...
git commit -m "Fixed bug"
git checkout feature-branch # Back to your feature
git stash pop # Get your work back
With a message:
git stash save "Working on login feature"
2. git branch – Working with Branches
What it does: Create, list, and manage branches
# List all branches
git branch # Local branches
git branch -a # All branches (local + remote)
# Create a new branch
git branch feature-name
# Switch to a branch
git checkout feature-name
# OR (newer way)
git switch feature-name
# Create and switch in one command
git checkout -b feature-name
# OR
git switch -c feature-name
# Delete a branch
git branch -d feature-name # Safe delete (only if merged)
git branch -D feature-name # Force delete (even if not merged)
# Rename current branch
git branch -m new-name
Example:
# Create a branch for a new feature
git branch add-user-profile
git checkout add-user-profile
# Work on your feature...
git add .
git commit -m "Added user profile"
# Switch back to main
git checkout main
# Merge your feature
git merge add-user-profile
# Delete the branch (no longer needed)
git branch -d add-user-profile
3. git merge – Combine Branches
What it does: Combines changes from one branch into another
# Merge a branch into current branch
git merge branch-name
# Merge with a message
git merge branch-name -m "Merge feature branch"
Example:
# You're on main branch
git checkout main
git merge feature-branch
# Now main has all changes from feature-branch
Merge conflicts? Git will mark them. Edit files, then:
git add conflicted-file.py
git commit -m "Resolved merge conflict"
4. git reset – Undo Commits
β οΈ Warning: Use carefully! Can lose work.
# Soft reset (keeps changes, unstages them)
git reset --soft HEAD~1 # Undo last commit, keep changes staged
git reset --soft HEAD~2 # Undo last 2 commits
# Mixed reset (default - keeps changes, unstages them)
git reset HEAD~1 # Undo last commit, keep changes in working directory
git reset HEAD~2 # Undo last 2 commits
# Hard reset (β οΈ DESTROYS changes)
git reset --hard HEAD~1 # Undo last commit, DELETE all changes
git reset --hard origin/main # Reset to match remote exactly
Example:
# Oops, wrong commit message
git reset --soft HEAD~1
git commit -m "Correct message"
# Undo last commit but keep changes
git reset HEAD~1
# Now you can edit and recommit
β οΈ Never do git reset --hard on shared branches!
5. git revert – Safely Undo Commits
What it does: Creates a new commit that undoes changes (safer than reset)
# Revert last commit
git revert HEAD
# Revert a specific commit
git revert abc1234
# Revert without committing (review first)
git revert --no-commit abc1234
Example:
# You committed something by mistake
git revert HEAD
# Creates a new commit that undoes the mistake
# History is preserved (good for shared branches)
Why use revert instead of reset?
- β Safe for shared branches
- β Preserves history
- β Can be undone easily
6. git restore – Restore Files
What it does: Restore files to a previous state
# Discard changes in working directory
git restore file.txt
# Discard all changes
git restore .
# Restore from staging area
git restore --staged file.txt
# Restore from a specific commit
git restore --source=HEAD~1 file.txt
Example:
# You edited a file but want to undo changes
git restore index.html
# You staged a file but want to unstage it
git restore --staged index.html
7. git clean – Remove Untracked Files
What it does: Removes files Git doesn’t track
# See what would be removed (dry run)
git clean -n
# Remove untracked files
git clean -f
# Remove untracked files and directories
git clean -fd
# Interactive mode (asks for each file)
git clean -i
Example:
# You created test files you don't need
git clean -n # Preview what will be deleted
git clean -f # Actually delete them
β οΈ Warning: This permanently deletes files!
8. .gitignore – Ignore Files
What it does: Tells Git to ignore certain files/folders
Create .gitignore file:
# Python
__pycache__/
*.pyc
*.pyo
venv/
env/
# Node.js
node_modules/
npm-debug.log
# IDE
.vscode/
.idea/
*.swp
# OS
.DS_Store
Thumbs.db
# Environment variables
.env
.env.local
# Logs
*.log
logs/
# Build files
dist/
build/
*.egg-info/
Example:
# Create .gitignore
echo "venv/" > .gitignore
echo "*.pyc" >> .gitignore
# Now Git will ignore these files
git status # They won't show up
9. git show – View Commit Details
What it does: Shows detailed information about a commit
# Show last commit
git show
# Show specific commit
git show abc1234
# Show just the files changed
git show --stat abc1234
# Show just the diff
git show abc1234
Example:
git show HEAD
# Shows: author, date, message, and all changes
10. git blame – See Who Changed What
What it does: Shows who last modified each line of a file
# See blame for a file
git blame file.txt
# See blame for specific lines
git blame -L 10,20 file.txt
Example:
git blame index.html
# Output:
# abc1234 (John Doe 2024-12-25 10:30:00) <h1>Title</h1>
# def5678 (Jane Smith 2024-12-24 15:20:00) <p>Content</p>
Useful for: Finding who to ask about code
11. git cherry-pick – Apply Specific Commits
What it does: Applies a commit from one branch to another
# Apply a commit to current branch
git cherry-pick abc1234
# Apply multiple commits
git cherry-pick abc1234 def5678
# Apply without committing (review first)
git cherry-pick -n abc1234
Example:
# You're on main branch
# You want a specific commit from feature branch
git cherry-pick abc1234
# Now that commit is on main too
12. git tag – Mark Important Points
What it does: Creates tags for releases/versions
# 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"
# List tags
git tag
# Push tags to remote
git push origin v1.0.0
git push origin --tags # Push all tags
# Delete a tag
git tag -d v1.0.0
git push origin --delete v1.0.0
Example:
# You finished version 1.0
git tag -a v1.0.0 -m "First stable release"
git push origin v1.0.0
13. git reflog – Recovery Tool
What it does: Shows history of all Git operations (even deleted commits!)
Useful for: Recovering “lost” commits
# See reflog
git reflog
# Recover a "lost" commit
git reflog
# Find the commit hash
git checkout abc1234
# Or create a branch from it
git branch recovered-branch abc1234
Example:
# You accidentally deleted a branch
git reflog
# Find the commit before deletion
git checkout abc1234
git branch recovered-feature
π Quick Reference
Essential Commands
# Setup
git config --global user.name "Your Name"
git config --global user.email "your@email.com"
# Create/Clone
git init # Start new repo
git clone <url> # Copy repo from GitHub
# Daily Work
git status # See what changed
git add <file> # Stage file
git add . # Stage all changes
git commit -m "message" # Save changes
git log # View history
git log --oneline # Compact history
# Remote Operations
git remote -v # See remotes
git fetch origin # Check what's new (safe)
git pull origin main # Download and merge
git push origin main # Upload changes
# Comparing
git diff # See uncommitted changes
git diff --staged # See staged changes
git diff HEAD origin/main # Compare local vs remote
git log HEAD..origin/main # See commits on remote
# Stashing
git stash # Save changes temporarily
git stash list # List stashes
git stash pop # Get changes back
git stash apply # Apply but keep stash
git stash drop # Delete a stash
# Branches
git branch # List branches
git branch <name> # Create branch
git checkout <name> # Switch branch
git switch <name> # Switch branch (newer)
git checkout -b <name> # Create and switch
git branch -d <name> # Delete branch
git merge <branch> # Merge branch
# Undoing
git restore <file> # Discard file changes
git restore --staged <file> # Unstage file
git reset HEAD~1 # Undo commit (keep changes)
git reset --soft HEAD~1 # Undo commit (keep staged)
git reset --hard HEAD~1 # β οΈ Undo commit (DELETE changes)
git revert HEAD # Safely undo commit
# Cleaning
git clean -n # Preview untracked files
git clean -f # Remove untracked files
git clean -fd # Remove files and directories
# Viewing
git show # Show last commit details
git show <commit> # Show specific commit
git blame <file> # See who changed what
git reflog # Recovery tool
# Advanced
git cherry-pick <commit> # Apply specific commit
git tag v1.0.0 # Create tag
git tag -a v1.0.0 -m "msg" # Annotated tag
π Practice Exercises
Exercise 1: Create Your First Repo
# 1. Create a folder
mkdir git-practice
cd git-practice
# 2. Initialize Git
git init
# 3. Create a file
echo "Hello Git!" > hello.txt
# 4. Add and commit
git add hello.txt
git commit -m "First commit"
# 5. Check history
git log --oneline
Exercise 2: Make Changes
# 1. Edit the file
echo "Hello Git! This is my second change." > hello.txt
# 2. See what changed
git status
git diff
# 3. Commit the change
git add hello.txt
git commit -m "Updated hello message"
# 4. See history
git log --oneline
Exercise 3: Connect to GitHub
# 1. Create repo on GitHub (via website)
# 2. Connect local to remote
git remote add origin https://github.com/yourusername/git-practice.git
# 3. Push your code
git push -u origin main
# 4. Check on GitHub - your code should be there!
π‘ Pro Tips
- Always pull before pushΒ – Avoid conflicts
- Write good commit messagesΒ – Future you will thank you
- Commit oftenΒ – Small commits are easier to understand
- UseΒ
git statusΒ frequentlyΒ – Know what’s happening - Fetch before pullΒ – See what will change first
- Don’t commit sensitive dataΒ – UseΒ
.gitignore - Use branches for featuresΒ – Keep main stable
- Use stash for quick switchesΒ – Don’t commit incomplete work
- Use revert, not resetΒ – On shared branches
- Check reflogΒ – Before panicking about lost work
- Preview before cleanΒ – Always useΒ
git clean -nΒ first - Tag releasesΒ – Mark important versions
π Summary
The Git Workflow
1. git pull # Get latest changes
2. Make changes # Edit your code
3. git status # See what changed
4. git add . # Stage changes
5. git commit -m "" # Save changes
6. git push # Upload to GitHub
Key Concepts
- LocalΒ = Your computer
- RemoteΒ = GitHub (cloud)
- CommitΒ = Save a snapshot
- PushΒ = Upload to GitHub
- PullΒ = Download from GitHub
- FetchΒ = Check what’s new (safe)
π Congratulations!
You now understand Git! Practice with small projects, and it will become second nature.
Remember: Git is a tool – the more you use it, the more comfortable you’ll become!
π Additional Resources
- Official Git Documentation:Β https://git-scm.com/doc
- GitHub Guides:Β https://guides.github.com
- Visual Git Guide:Β https://learngitbranching.js.org
- Git Cheat Sheet:Β https://education.github.com/git-cheat-sheet-education.pdf
Happy Coding! π
