๐Ÿ“ฆ Git & GitHub Complete Guide

Your interactive journey to version control mastery

Lesson 1 of 11

Introduction to Git

What is Git?

Git is a distributed version control system that tracks changes in your code over time. Think of it as a time machine for your code - you can see what changed, who changed it, and go back to any previous version whenever you want!

Why Should You Learn Git?

  • Track Changes: Every modification to your code is recorded with a message explaining what and why
  • Collaborate Efficiently: Multiple developers can work on the same project without stepping on each other's toes
  • Backup & Safety: Your code is safely stored and you can always revert mistakes
  • Experiment Freely: Try new features in separate branches without affecting the main code
  • Professional Standard: Git is used by virtually every tech company and open-source project

Git vs GitHub

Git GitHub
Version control system (software) Web-based hosting service for Git repositories
Runs locally on your computer Cloud-based platform accessible anywhere
Command-line tool Provides GUI, collaboration features, CI/CD
Free and open-source Free for public repos, paid plans available
๐Ÿ’ก Quick Analogy: Git is like Microsoft Word's "Track Changes" feature, but infinitely more powerful. GitHub is like Google Drive where you store and share those documents with your team!

How Git Works

Git uses a three-stage workflow:

  1. Working Directory: Where you edit files on your computer
  2. Staging Area: Where you prepare files before saving them
  3. Repository: Where Git permanently stores the snapshots of your project
๐Ÿ“ Remember: Git doesn't automatically track everything. You choose what to track, when to save snapshots (commits), and what to share with others!
Lesson 2 of 11

Installation & Setup

Installing Git

Let's get Git installed on your machine. Choose your operating system:

๐ŸชŸ Windows

Option 1: Download from official website

Visit: https://git-scm.com/download/win

Option 2: Use Windows Package Manager

winget install --id Git.Git -e --source winget

๐ŸŽ macOS

brew install git

# Requires Homebrew package manager

๐Ÿง Linux (Ubuntu/Debian)

sudo apt update sudo apt install git

Verify Installation

After installing, verify Git is working:

git --version

# Should output: git version 2.x.x

Initial Configuration

Configure Git with your identity. This information will be attached to every commit you make:

git config --global user.name "Your Name" git config --global user.email "your.email@example.com"
โš ๏ธ Important: Use the same email address you'll use for GitHub to ensure proper attribution of your commits!

Optional Configuration

Set your default text editor (VS Code example):

git config --global core.editor "code --wait"

Check Your Configuration

git config --list

# View all Git settings

git config user.name

# Check specific setting

๐Ÿ’ก Pro Tip: The --global flag applies settings to all repositories on your computer. You can override these per-repository by omitting the flag!
Lesson 3 of 11

Git Basics

Creating Your First Repository

There are two ways to start with Git:

Method 1: Initialize a New Repository

Start tracking an existing project:

cd your-project-folder git init

# Creates a .git folder to track changes

Method 2: Clone an Existing Repository

Download a project from GitHub:

git clone https://github.com/username/repository.git git clone https://github.com/username/repository.git my-folder

# Clone into a specific folder name

The Git Workflow

Understanding the three-stage workflow is crucial:

  1. Working Directory โ†’ Make changes to files
  2. Staging Area โ†’ Select which changes to include
  3. Repository โ†’ Permanently save the snapshot

Check Status

Always start by checking what's changed:

git status

# Shows: modified files, staged changes, current branch

Stage Changes

Add files to the staging area:

git add filename.txt

# Stage a specific file

git add .

# Stage all changes in current directory

git add *.js

# Stage all JavaScript files

git add -A

# Stage all changes including deletions

Commit Changes

Save your staged changes permanently:

git commit -m "Add user authentication feature" git commit -am "Fix login bug"

# Stage and commit tracked files in one step

๐Ÿ’ก Writing Good Commit Messages:
  • Use present tense: "Add" not "Added"
  • Be specific: "Fix login validation bug" not "Fix bug"
  • Keep first line under 50 characters
  • Explain what and why, not how

View History

git log

# Full commit history

git log --oneline

# Compact view

git log --graph --oneline --all

# Visual branch graph

View Changes

git diff

# See unstaged changes

git diff --staged

# See staged changes

git show commit-hash

# See specific commit details

Undo Changes

git restore filename.txt

# Discard changes in working directory

git restore --staged filename.txt

# Unstage file (keep changes)

git reset HEAD~1

# Undo last commit, keep changes

โš ๏ธ Be Careful: git reset --hard permanently deletes changes. Always make sure you don't need those changes before using it!
Lesson 4 of 11

Branching & Merging

What Are Branches?

Branches are independent lines of development. Think of them as parallel universes for your code where you can experiment without affecting the main project!

Use branches for:

  • Developing new features without breaking existing code
  • Fixing bugs in isolation
  • Experimenting with new ideas safely
  • Collaborating with teammates on different tasks
  • Maintaining multiple versions of your project
๐Ÿ’ก Real-World Analogy: Imagine writing a novel. Branches let you try different story endings without deleting your original. Once you pick the best ending, you merge it back into the main story!

Viewing Branches

See all your branches and identify which one you're currently on:

git branch

# List local branches (* shows current)

git branch -a

# List all branches (including remote)

git branch -v

# Show last commit on each branch

git branch -r

# List only remote branches

Creating Branches

Create new branches for your features or experiments:

git branch feature/user-auth

# Create new branch (stay on current branch)

git checkout -b feature/user-auth

# Create and switch in one command

git switch -c feature/user-auth

# Modern way (Git 2.23+) - recommended

๐Ÿ’ก Branch Naming Convention:
  • feature/feature-name - for new features
  • fix/bug-description - for bug fixes
  • hotfix/urgent-fix - for urgent production fixes
  • refactor/code-improvement - for refactoring
  • experiment/idea-name - for experiments

Switching Branches

Move between different branches:

git checkout main

# Classic way

git switch main

# Modern way (recommended)

git switch -

# Switch to previous branch (like cd -)

๐Ÿ“ Important: Always commit or stash your changes before switching branches! Uncommitted changes might cause conflicts or be lost.

Renaming Branches

git branch -m old-name new-name

# Rename any branch

git branch -m new-name

# Rename current branch

Merging Branches

Once your feature is complete and tested, merge it back into the main branch:

git checkout main

# Switch to the branch you want to merge INTO

git pull

# Make sure main is up-to-date

git merge feature/user-auth

# Merge feature branch into main

Types of Merges

1. Fast-Forward Merge

When no changes were made to the base branch, Git simply moves the pointer forward:

git merge feature-branch

# Git will fast-forward if possible

2. No-Fast-Forward Merge

Create a merge commit even when fast-forward is possible (preserves branch history):

git merge --no-ff feature-branch

# Always creates a merge commit

3. Squash Merge

Combine all commits from the feature branch into one commit:

git merge --squash feature-branch

# Squash all commits into one

git commit -m "Add complete user authentication"

# Commit the squashed changes

Handling Merge Conflicts

When Git can't automatically merge changes, you'll see conflict markers in your files:

Conflict markers in your file:

<<<<<<< HEAD

Your current changes (in main branch)

=======

Incoming changes (from feature branch)

>>>>>>> feature-branch

Steps to Resolve Conflicts:

  1. Identify conflicted files: git status
  2. Open conflicted files in your code editor
  3. Decide which changes to keep:
    • Keep your changes (HEAD)
    • Keep their changes (incoming)
    • Keep both (combine manually)
    • Write something completely new
  4. Remove conflict markers (<<<<<<<, =======, >>>>>>>)
  5. Stage resolved files: git add filename
  6. Complete the merge: git commit

# View conflicted files

git status

# After resolving conflicts manually

git add . git commit -m "Resolve merge conflicts"

# Or abort the merge

git merge --abort

# Cancel merge and return to previous state

๐Ÿ’ก Pro Tips for Avoiding Conflicts:
  • Pull from main frequently to stay updated
  • Keep feature branches small and short-lived
  • Communicate with team about file changes
  • Use git merge --no-commit --no-ff to preview merge before committing

Merge Tools

Use visual merge tools for complex conflicts:

git mergetool

# Opens configured merge tool (e.g., VS Code, Meld)

git config --global merge.tool vscode

# Set VS Code as default merge tool

Deleting Branches

Clean up merged branches to keep your repository organized:

git branch -d feature/user-auth

# Delete merged branch (safe)

git branch -D feature/user-auth

# Force delete unmerged branch โš ๏ธ

git push origin --delete feature/user-auth

# Delete remote branch

๐Ÿ“ Best Practice: Always delete branches after merging to keep your repository clean. Don't worry - the commit history is preserved even after deleting the branch!

Viewing Merge History

git log --graph --oneline --all

# Visual branch history

git log --merges

# Show only merge commits

git show-branch

# Show branch relationships

Common Branching Workflow

# Step 1: Create and switch to feature branch

git checkout main git pull git checkout -b feature/payment-integration

# Step 2: Make changes and commit

# ...write code...

git add . git commit -m "Add payment gateway integration"

# Step 3: Push feature branch

git push -u origin feature/payment-integration

# Step 4: After review, merge to main

git checkout main git pull git merge feature/payment-integration git push

# Step 5: Cleanup

git branch -d feature/payment-integration git push origin --delete feature/payment-integration
โš ๏ธ Common Mistakes to Avoid:
  • Don't merge main into your feature branch multiple times (use rebase instead)
  • Don't force-delete branches with -D unless you're sure
  • Don't forget to pull before merging
  • Don't leave too many feature branches hanging around
Lesson 5 of 11

Working with Remotes

What Are Remotes?

Remote repositories are versions of your project hosted on the internet or network. They enable collaboration by allowing multiple developers to work on the same project from different locations!

๐Ÿ’ก Think of Remotes as: Cloud storage for your Git repository. Just like Dropbox or Google Drive, but specifically designed for code with full version control!

Viewing Remotes

Check which remote repositories are connected to your project:

git remote

# List all remotes (just names)

git remote -v

# Show remote URLs (fetch and push)

git remote show origin

# Detailed info about a specific remote

Adding a Remote

Connect your local repository to a remote server (like GitHub, GitLab, or Bitbucket):

git remote add origin https://github.com/username/repo.git

# Add remote named 'origin' (standard convention)

git remote add upstream https://github.com/original/repo.git

# Add upstream remote (for forked repos)

๐Ÿ“ Origin vs Upstream:
  • origin - Your main remote (usually your GitHub repo)
  • upstream - Original repo you forked from (for contributing to open source)

Cloning a Repository

Download a complete copy of a remote repository to your local machine:

git clone https://github.com/username/repo.git

# Clone into a folder named 'repo'

git clone https://github.com/username/repo.git my-project

# Clone into custom folder name

git clone -b develop https://github.com/username/repo.git

# Clone specific branch

git clone --depth 1 https://github.com/username/repo.git

# Shallow clone (only latest commit, faster)

Fetching Changes

Fetch downloads changes from remote but doesn't merge them (safe to check what's new):

git fetch

# Fetch all branches from origin

git fetch origin

# Fetch from specific remote

git fetch origin main

# Fetch specific branch

git fetch --all

# Fetch from all remotes

git fetch --prune

# Remove deleted remote branches

Pulling Changes

Pull = Fetch + Merge (downloads and automatically merges into current branch):

git pull

# Pull from tracking branch

git pull origin main

# Pull from specific remote and branch

git pull --rebase

# Pull and rebase instead of merge

git pull --no-commit

# Pull but don't auto-commit merge

๐Ÿ’ก Fetch vs Pull:
  • git fetch - Safe, just downloads. You review then merge manually
  • git pull - Convenient, downloads AND merges automatically
  • Use fetch when you want to be careful, pull when you trust the changes

Pushing Changes

Upload your local commits to the remote repository:

git push

# Push to tracking branch

git push origin main

# Push to specific remote and branch

git push -u origin feature-branch

# Push and set upstream tracking

git push --all

# Push all branches

git push --tags

# Push all tags

๐Ÿ“ The -u Flag: git push -u origin branch-name sets up tracking so future git push and git pull commands know where to go automatically!

Force Pushing

โš ๏ธ Dangerous Operation! Force push overwrites remote history. Use with extreme caution!
git push --force

# Force push (DANGEROUS - overwrites remote)

git push --force-with-lease

# Safer - only if no one else pushed

Only use force push when:

  • You're working on your own feature branch
  • You've accidentally pushed sensitive data
  • You need to fix commit history on your branch
  • NEVER force push to main/master or shared branches!

Managing Remotes

Renaming a Remote

git remote rename old-name new-name

# Change remote name

Changing Remote URL

git remote set-url origin https://github.com/new-url/repo.git

# Update remote URL (e.g., switching from HTTPS to SSH)

Removing a Remote

git remote remove origin

# Remove remote connection

Tracking Branches

Set up your local branch to track a remote branch:

git branch -vv

# Show which remote branches are tracked

git branch --set-upstream-to=origin/main

# Set tracking for current branch

git checkout --track origin/feature-branch

# Create local branch tracking remote

Working with Multiple Remotes

You can have multiple remotes (useful for forks and collaboration):

git remote add origin https://github.com/you/repo.git git remote add upstream https://github.com/original/repo.git

# Fetch from upstream

git fetch upstream

# Merge upstream changes into your branch

git merge upstream/main

# Push to your fork

git push origin main

Checking Remote Status

git remote show origin

# Detailed information about remote

git ls-remote

# List all remote branches and tags

git branch -r

# List all remote branches

Common Remote Workflow

# 1. Start your workday - get latest changes

git checkout main git pull origin main

# 2. Create feature branch

git checkout -b feature/new-feature

# 3. Make changes and commit

git add . git commit -m "Add new feature"

# 4. Push to remote (first time)

git push -u origin feature/new-feature

# 5. Continue working - subsequent pushes

git push

# 6. Stay updated with main

git checkout main git pull git checkout feature/new-feature git merge main

Troubleshooting Common Issues

Rejected Push (Remote has changes you don't have)

Error: ! [rejected] main -> main (non-fast-forward)

# Solution: Pull first, then push

git pull origin main git push origin main

Authentication Issues

# Switch from HTTPS to SSH for easier authentication

git remote set-url origin git@github.com:username/repo.git

# Or use GitHub CLI for HTTPS

gh auth login

Accidentally Pushed to Wrong Branch

# Reset remote branch to previous state

git push origin HEAD^:branch-name --force
๐Ÿ’ก Best Practices:
  • Always git pull before starting work
  • Commit and push your work regularly (don't lose progress!)
  • Use git fetch to see what's new without merging
  • Never force push to shared branches
  • Use descriptive branch names that match remote conventions
  • Keep your local main/master in sync with remote
Lesson 6 of 11

GitHub Essentials

What is GitHub?

GitHub is a web-based platform built on top of Git that provides hosting for Git repositories plus powerful collaboration features. Think of it as social media for developers where you can share code, collaborate on projects, and contribute to open source!

๐Ÿ’ก GitHub = Git + Hub
Git (version control) + Hub (central place where developers connect)

Creating a Repository on GitHub

Two ways to start:

Method 1: Create on GitHub First

1. Go to github.com โ†’ Click "New repository"

2. Choose name, description, public/private

3. Initialize with README (optional)

4. Clone to your computer:

git clone https://github.com/username/repo-name.git

Method 2: Push Existing Local Repo

1. Create empty repo on GitHub (no README)

2. In your local project:

git remote add origin https://github.com/username/repo-name.git git branch -M main git push -u origin main

Pull Requests (PRs)

Pull Requests are GitHub's way of proposing changes. They're essential for team collaboration!

Creating a Pull Request

  1. Create a branch for your changes
  2. Make commits and push to GitHub
  3. Open PR on GitHub comparing your branch to main
  4. Request review from team members
  5. Address feedback with additional commits
  6. Merge when approved!

# Complete PR workflow

git checkout -b feature/add-login

# Make your changes

git add . git commit -m "Add user login feature" git push -u origin feature/add-login

# Then go to GitHub and click "Compare & pull request"

๐Ÿ’ก PR Best Practices:
  • Write clear PR title and description
  • Keep PRs small and focused (easier to review)
  • Link related issues (#123)
  • Add screenshots for UI changes
  • Request specific reviewers
  • Be responsive to feedback

Code Review

Reviewing others' code is crucial for maintaining quality:

How to Review a PR

  • Read the description - understand what's being changed
  • Check the code - look for bugs, style issues, improvements
  • Test locally - pull the branch and run it
  • Leave comments - be constructive and specific
  • Approve or request changes

# Test someone's PR locally

git fetch origin pull/123/head:pr-123 git checkout pr-123

# Or use GitHub CLI

gh pr checkout 123

Issues & Project Management

GitHub Issues are like a built-in task tracker for your project:

Creating Issues

  • Bug reports - document problems with code
  • Feature requests - suggest new functionality
  • Questions - ask for help or clarification
  • Tasks - track work items
๐Ÿ“ Issue Templates: Create templates for bug reports and feature requests to ensure consistent, detailed issues!

Linking Issues & PRs

In commit messages or PR descriptions:

git commit -m "Fix login bug - closes #42"

# When merged, issue #42 auto-closes!

Magic keywords that auto-close issues:

  • closes #123
  • fixes #123
  • resolves #123

Forking & Contributing

Fork repositories to contribute to open source projects:

Contributing to Open Source

# 1. Fork the repo on GitHub (click Fork button)

# 2. Clone YOUR fork

git clone https://github.com/YOUR-USERNAME/repo.git cd repo

# 3. Add original repo as upstream

git remote add upstream https://github.com/ORIGINAL-OWNER/repo.git

# 4. Create branch and make changes

git checkout -b fix-typo

# Make your changes

git commit -m "Fix typo in documentation"

# 5. Push to YOUR fork

git push origin fix-typo

# 6. Open PR on GitHub from your fork to original repo

Keeping Fork in Sync

git fetch upstream git checkout main git merge upstream/main git push origin main

GitHub Actions (CI/CD)

Automate testing, building, and deployment with GitHub Actions:

Create .github/workflows/test.yml:

name: Run Tests
on: [push, pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Run tests
        run: npm test

Common use cases:

  • Run tests on every push
  • Deploy to production when merging to main
  • Check code style and linting
  • Build documentation automatically
  • Send notifications to Slack/Discord

GitHub Pages

Host static websites directly from your repository for FREE!

1. Create a branch called "gh-pages" (or use main)

git checkout -b gh-pages git push origin gh-pages

2. Go to Settings โ†’ Pages โ†’ Select branch

3. Your site will be at: username.github.io/repo-name

README.md Best Practices

Your README is the front page of your project. Make it great!

# Project Name

Brief description of what your project does

## Features
- Feature 1
- Feature 2

## Installation
```bash
npm install
```

## Usage
```bash
npm start
```

## Contributing
Pull requests welcome!

## License
MIT
๐Ÿ’ก README Enhancements:
  • Add badges (build status, version, license)
  • Include screenshots/GIFs for visual projects
  • Write clear installation instructions
  • Provide usage examples
  • Add contributing guidelines
  • Specify license

GitHub CLI (gh)

Work with GitHub from your terminal:

gh repo create my-project --public

# Create repo from terminal

gh pr create --title "Add feature" --body "Description"

# Create PR from terminal

gh pr list

# List open PRs

gh pr checkout 123

# Checkout PR locally

gh issue create --title "Bug report"

# Create issue from terminal

gh issue list

# List issues

SSH Keys for GitHub

Set up SSH for password-free authentication:

# 1. Generate SSH key

ssh-keygen -t ed25519 -C "your-email@example.com"

# 2. Start SSH agent

eval "$(ssh-agent -s)" ssh-add ~/.ssh/id_ed25519

# 3. Copy public key

cat ~/.ssh/id_ed25519.pub

# Copy output and add to GitHub โ†’ Settings โ†’ SSH Keys

# 4. Test connection

ssh -T git@github.com

Repository Settings

Important settings to configure:

  • Branch Protection - Require PR reviews before merging to main
  • Required Checks - Tests must pass before merging
  • Code Owners - Auto-assign reviewers for specific files
  • Secrets - Store API keys securely for Actions
  • Collaborators - Add team members with different permissions

GitHub Gists

Share code snippets quickly:

Go to gist.github.com

- Create public or secret gists

- Share code snippets, configs, notes

- Clone gists like regular repos

git clone https://gist.github.com/username/gist-id.git
โš ๏ธ Security Best Practices:
  • Never commit API keys, passwords, or secrets
  • Use .gitignore for sensitive files
  • Use GitHub Secrets for Actions
  • Enable 2FA (Two-Factor Authentication)
  • Review third-party app access regularly
  • Use SSH keys instead of password authentication
๐Ÿ’ก GitHub Power User Tips:
  • Press . on any repo to open in VS Code web editor
  • Press t to search files in a repo
  • Press ? to see all keyboard shortcuts
  • Use @mentions to tag people in issues/PRs
  • Create custom labels for better organization
  • Use GitHub Projects for Kanban-style task management
  • Star repos you find useful (builds your profile!)
Lesson 7 of 11

Advanced Commands

Git Rebase

Rebase rewrites commit history by moving commits to a new base. It creates a cleaner, linear history compared to merge!

๐Ÿ’ก Rebase vs Merge:
Merge: Preserves history, creates merge commits
Rebase: Rewrites history, creates linear timeline

Basic Rebase

git checkout feature-branch git rebase main

# Moves feature-branch commits on top of main

Interactive Rebase

Powerful tool to edit, reorder, squash, or delete commits:

git rebase -i HEAD~3

# Interactive rebase last 3 commits

git rebase -i main

# Rebase all commits since main

Interactive rebase commands:

  • pick - Keep commit as is
  • reword - Change commit message
  • edit - Pause to amend commit
  • squash - Combine with previous commit
  • fixup - Like squash but discard message
  • drop - Remove commit
โš ๏ธ Golden Rule of Rebase: Never rebase commits that have been pushed to a shared/public branch! Only rebase your local, unpushed commits.

Git Stash

Temporarily save uncommitted changes without committing them:

git stash

# Stash current changes

git stash save "WIP: working on feature"

# Stash with descriptive message

git stash list

# View all stashes

git stash pop

# Apply and remove most recent stash

git stash apply

# Apply stash but keep it in stash list

git stash apply stash@{2}

# Apply specific stash

git stash drop stash@{0}

# Delete specific stash

git stash clear

# Delete all stashes

๐Ÿ’ก When to use stash:
  • Need to switch branches but not ready to commit
  • Quick experiment without losing current work
  • Pull latest changes but have uncommitted work

Git Cherry-Pick

Copy specific commits from one branch to another:

git cherry-pick abc123

# Apply commit abc123 to current branch

git cherry-pick abc123 def456

# Cherry-pick multiple commits

git cherry-pick abc123..def456

# Cherry-pick range of commits

git cherry-pick --no-commit abc123

# Apply changes without committing

Git Reflog

Reflog is Git's safety net - it records every HEAD movement. Use it to recover "lost" commits!

git reflog

# Show history of HEAD movements

git reflog show feature-branch

# Show reflog for specific branch

git reset --hard HEAD@{2}

# Undo to specific reflog entry

๐Ÿ“ Recovering Lost Commits: If you accidentally deleted a branch or reset too far, use git reflog to find the commit hash and git checkout or git reset to recover it!

Git Bisect

Binary search to find which commit introduced a bug:

git bisect start git bisect bad

# Mark current commit as bad

git bisect good abc123

# Mark known good commit

# Git checks out middle commit - test it

git bisect good

# If works - mark good

git bisect bad

# If broken - mark bad

# Repeat until Git finds the culprit commit

git bisect reset

# Return to original branch

Git Blame

See who last modified each line of a file (not for blaming, but understanding!):

git blame filename.js

# Show author and commit for each line

git blame -L 10,20 filename.js

# Blame specific line range

git blame -e filename.js

# Show email addresses

Git Clean

Remove untracked files and directories:

git clean -n

# Dry run - show what would be deleted

git clean -f

# Force delete untracked files

git clean -fd

# Delete untracked files and directories

git clean -fX

# Delete only ignored files

โš ๏ธ Warning: git clean permanently deletes files! Always use -n first to preview what will be deleted.

Git Tags

Mark specific points in history (usually for releases):

git tag v1.0.0

# Create lightweight tag

git tag -a v1.0.0 -m "Release version 1.0.0"

# Create annotated tag (recommended)

git tag

# List all tags

git show v1.0.0

# Show tag details

git push origin v1.0.0

# Push specific tag

git push origin --tags

# Push all tags

git tag -d v1.0.0

# Delete local tag

git push origin --delete v1.0.0

# Delete remote tag

Git Submodules

Include other Git repositories within your repository:

git submodule add https://github.com/user/repo.git path/to/submodule

# Add submodule

git clone --recurse-submodules https://github.com/user/repo.git

# Clone repo with submodules

git submodule update --init --recursive

# Initialize and update submodules

git submodule update --remote

# Update submodules to latest

Git Worktree

Work on multiple branches simultaneously without switching:

git worktree add ../project-feature feature-branch

# Create worktree in different directory

git worktree list

# List all worktrees

git worktree remove ../project-feature

# Remove worktree

Git Hooks

Automate tasks at specific Git events:

Hooks are scripts in .git/hooks/

Common hooks:

- pre-commit: Run tests before commit

- pre-push: Run checks before push

- commit-msg: Validate commit message format

- post-merge: Run after merge (npm install, etc.)

Git Archive

Create a zip/tar archive of your repository:

git archive --format=zip --output=project.zip main

# Create zip of main branch

git archive --format=tar --output=project.tar HEAD

# Create tar of current commit

Git Grep

Search through your repository faster than regular grep:

git grep "function"

# Search for "function" in tracked files

git grep -n "TODO"

# Show line numbers

git grep --count "import"

# Count matches per file

Amending Commits

git commit --amend

# Modify last commit message

git commit --amend --no-edit

# Add staged changes to last commit

git commit --amend --author="Name "

# Change author of last commit

๐Ÿ“ Note: Only amend commits that haven't been pushed! Amending changes the commit hash, which rewrites history.

Advanced Reset Options

git reset --soft HEAD~1

# Undo commit, keep changes staged

git reset --mixed HEAD~1

# Undo commit, keep changes unstaged (default)

git reset --hard HEAD~1

# Undo commit, discard all changes โš ๏ธ

git reset --hard origin/main

# Match local branch to remote exactly

Patch Files

Share changes without pushing:

git diff > changes.patch

# Create patch file

git apply changes.patch

# Apply patch

git format-patch HEAD~3

# Create patches for last 3 commits

git am *.patch

# Apply all patch files

๐Ÿ’ก Pro Tips:
  • Use git rebase -i to clean up commits before pushing
  • git reflog is your safety net - use it when things go wrong
  • Stash often when switching contexts quickly
  • Use annotated tags for releases (-a flag)
  • Practice advanced commands on test repos first!
  • Set up Git aliases for commonly used advanced commands
Lesson 8 of 11

Git Workflows

What Are Git Workflows?

Git workflows are standardized strategies for how teams organize branches, collaborate, and release code. Choosing the right workflow depends on your team size, project type, and deployment process.

๐Ÿ’ก No "Perfect" Workflow: The best workflow is the one that fits your team's needs. Start simple, then adapt as you grow!

1. Centralized Workflow

Simplest workflow - everyone works on main branch. Good for small teams or transitioning from SVN.

How It Works

git pull origin main

# Get latest changes

# Make changes locally

git add . git commit -m "Add feature" git pull origin main

# Pull again before pushing

git push origin main

Pros: Simple, easy to learn, minimal overhead

Cons: No isolation, conflicts more common, risky for production

2. Feature Branch Workflow

Each feature gets its own branch. Most popular workflow for teams of any size!

How It Works

# 1. Start from main

git checkout main git pull origin main

# 2. Create feature branch

git checkout -b feature/user-authentication

# 3. Work and commit

git add . git commit -m "Implement login" git commit -m "Add password validation"

# 4. Push feature branch

git push -u origin feature/user-authentication

# 5. Create Pull Request on GitHub

# After approval, merge to main and delete branch

Pros: Isolated features, easy code review, safer than centralized

Cons: Merge conflicts if branches live too long

๐Ÿ“ Branch Naming Convention:
  • feature/ - New features
  • fix/ or bugfix/ - Bug fixes
  • hotfix/ - Urgent production fixes
  • refactor/ - Code improvements
  • docs/ - Documentation
  • test/ - Adding tests

3. Gitflow Workflow

Structured workflow with multiple long-lived branches. Great for scheduled releases and larger teams.

Branch Structure

  • main - Production-ready code only
  • develop - Integration branch for features
  • feature/* - New features (branch from develop)
  • release/* - Release preparation
  • hotfix/* - Emergency production fixes

Complete Gitflow Example

# Feature Development

git checkout develop git pull origin develop git checkout -b feature/new-dashboard

# Work on feature

git push -u origin feature/new-dashboard

# Create PR to develop (not main!)

# Release Process

git checkout develop git checkout -b release/1.2.0

# Final testing, bug fixes, version bumps

git checkout main git merge release/1.2.0 git tag v1.2.0 git checkout develop git merge release/1.2.0

# Hotfix (production emergency)

git checkout main git checkout -b hotfix/security-patch

# Fix critical bug

git checkout main git merge hotfix/security-patch git tag v1.2.1 git checkout develop git merge hotfix/security-patch

Pros: Very organized, clear release process, supports multiple versions

Cons: Complex for small teams, overhead with many branches

4. GitHub Flow

Simplified workflow perfect for continuous deployment. Used by GitHub themselves!

The Rules

  1. main branch is always deployable
  2. Create descriptive feature branches from main
  3. Push to remote regularly
  4. Open PR when ready for feedback
  5. Merge only after review and passing tests
  6. Deploy immediately after merging
git checkout main git pull origin main git checkout -b improve-search

# Make changes, commit, push

git push -u origin improve-search

# Open PR โ†’ Review โ†’ Merge โ†’ Deploy

Pros: Simple, fast deployment, works great with CI/CD

Cons: Requires good testing, not ideal for scheduled releases

5. Trunk-Based Development

Everyone commits to one branch (trunk or main) very frequently. Used by Google, Facebook!

Key Principles

  • Commit to main multiple times per day
  • Very short-lived feature branches (hours, not days)
  • Feature flags for incomplete features
  • Extensive automated testing
git checkout main git pull --rebase origin main

# Make small change

git add . git commit -m "Small incremental change" git pull --rebase origin main git push origin main

# Repeat frequently throughout the day

Pros: Fast integration, fewer merge conflicts, continuous delivery

Cons: Requires mature testing, feature flags, team discipline

6. Forking Workflow

Each developer has their own server-side fork. Common in open source projects.

# 1. Fork repo on GitHub

git clone https://github.com/YOUR-USERNAME/project.git cd project git remote add upstream https://github.com/ORIGINAL-OWNER/project.git

# 2. Work on feature

git checkout -b fix-bug

# Make changes

git push origin fix-bug

# 3. Create PR from your fork to original repo

# 4. Keep your fork synced

git fetch upstream git checkout main git merge upstream/main git push origin main

Choosing the Right Workflow

Workflow Best For
Centralized Small teams, learning Git, simple projects
Feature Branch Most teams, general purpose, balanced approach
Gitflow Scheduled releases, multiple versions, large teams
GitHub Flow Continuous deployment, web apps, fast iterations
Trunk-Based Mature teams, strong testing, continuous delivery
Forking Open source, external contributors

Release Management Strategies

Semantic Versioning (SemVer)

Version format: MAJOR.MINOR.PATCH (e.g., 2.4.1)

  • MAJOR - Breaking changes (1.0.0 โ†’ 2.0.0)
  • MINOR - New features, backward compatible (1.0.0 โ†’ 1.1.0)
  • PATCH - Bug fixes (1.0.0 โ†’ 1.0.1)
git tag -a v1.2.0 -m "Release version 1.2.0" git push origin v1.2.0

Team Collaboration Best Practices

๐Ÿ’ก Golden Rules:
  • main/master is sacred - Always keep it stable and deployable
  • Pull before push - Always sync before pushing your work
  • Small, frequent commits - Easier to review and revert
  • Descriptive branch names - team/feature/add-payment-gateway
  • Review before merge - Never merge your own PR without review
  • Clean up branches - Delete after merging
  • Communicate - Tell team about breaking changes

Commit Message Conventions

Consistent commit messages make history readable:

feat: Add user login functionality

- Implement JWT authentication
- Add login form validation
- Create user session management

Closes #123

Common prefixes:

  • feat: - New feature
  • fix: - Bug fix
  • docs: - Documentation
  • style: - Formatting, no code change
  • refactor: - Code restructuring
  • test: - Adding tests
  • chore: - Maintenance tasks

CI/CD Integration

Automate testing and deployment in your workflow:

Typical CI/CD pipeline:

1. Developer pushes to feature branch

2. CI runs tests automatically

3. Create PR when tests pass

4. Code review + approval

5. Merge triggers deployment to staging

6. Manual approval for production

7. Auto-deploy to production

๐Ÿ“ Workflow Tips:
  • Start simple, don't over-engineer
  • Document your workflow in README.md
  • Use branch protection rules on main
  • Set up status checks (tests must pass)
  • Require PR reviews before merging
  • Automate what you can (CI/CD, testing)
Lesson 9 of 11

Troubleshooting

Common Problems & Solutions

Even experienced developers run into Git issues. Here's how to solve the most common problems!

๐Ÿ’ก Golden Rule: Don't panic! Git rarely loses data permanently. Most issues can be fixed with the right commands.

1. "Detached HEAD" State

Problem: You're not on any branch, just at a specific commit.

Warning: HEAD is detached

# Solution 1: Create new branch from here

git checkout -b new-branch-name

# Solution 2: Return to a branch

git checkout main

2. Uncommitted Changes Blocking Checkout

Problem: Can't switch branches because of uncommitted changes.

error: Your local changes would be overwritten by checkout

# Solution 1: Stash changes

git stash git checkout other-branch git stash pop

# Apply stashed changes on new branch

# Solution 2: Commit changes first

git add . git commit -m "WIP: Save progress" git checkout other-branch

# Solution 3: Discard changes (โš ๏ธ CAREFUL!)

git checkout -- .

3. Merge Conflicts

Problem: Git can't automatically merge changes.

CONFLICT (content): Merge conflict in file.js

# Step 1: See conflicted files

git status

# Step 2: Edit files, remove conflict markers

Open file and choose which code to keep

# Step 3: Mark as resolved

git add file.js git commit -m "Resolve merge conflict"

# Or abort the merge

git merge --abort

4. Rejected Push (Non-Fast-Forward)

Problem: Remote has changes you don't have locally.

! [rejected] main -> main (non-fast-forward)

# Solution: Pull, then push

git pull origin main

# Resolve any conflicts if they occur

git push origin main

# Or use rebase for cleaner history

git pull --rebase origin main git push origin main

5. Accidentally Committed to Wrong Branch

Problem: Made commits on main instead of a feature branch.

# Solution: Move commits to new branch

git branch feature-branch

# Creates branch with current commits

git reset --hard HEAD~2

# Remove last 2 commits from main

git checkout feature-branch

# Switch to branch with your commits

6. Need to Undo Last Commit

Problem: Just committed but need to make changes.

# Keep changes, undo commit

git reset --soft HEAD~1

# Changes stay staged

# Keep changes, unstage them

git reset HEAD~1

# Changes become unstaged (default)

# Discard everything (โš ๏ธ DANGEROUS!)

git reset --hard HEAD~1

7. Accidentally Deleted Branch

Problem: Deleted a branch before merging it.

# Find the commit with reflog

git reflog

# Look for the branch's last commit

# Recreate branch at that commit

git branch recovered-branch abc123

# Replace abc123 with actual commit hash

8. Large File Causing Push Issues

Problem: File too large for GitHub (>100MB).

remote: error: File large-file.zip is 150MB; exceeds 100MB

# Solution 1: Remove from history

git filter-branch --tree-filter 'rm -f large-file.zip' HEAD

# Solution 2: Use BFG Repo-Cleaner (faster)

bfg --delete-files large-file.zip

# Solution 3: Use Git LFS for large files

git lfs install git lfs track "*.zip"

9. Corrupted Repository

Problem: Git reports corruption or broken objects.

# Step 1: Verify repository

git fsck --full

# Step 2: Try to recover

git gc --prune=now

# Step 3: Last resort - reclone

cd .. git clone https://github.com/user/repo.git repo-backup

# Copy uncommitted work from old repo

10. Authentication Failed

Problem: Can't push/pull due to authentication issues.

remote: Support for password authentication was removed

# Solution 1: Use Personal Access Token

Go to GitHub โ†’ Settings โ†’ Developer settings โ†’ Personal access tokens

Use token as password when prompted

# Solution 2: Switch to SSH

git remote set-url origin git@github.com:user/repo.git

# Solution 3: Use GitHub CLI

gh auth login

11. Staged Wrong Files

Problem: Accidentally staged files you don't want to commit.

# Unstage specific file

git reset HEAD file.txt

# Unstage all files

git reset HEAD .

12. Need to Edit Old Commit Message

Problem: Typo in commit message from several commits ago.

# Last commit - simple

git commit --amend

# Older commit - use interactive rebase

git rebase -i HEAD~5

# Change 'pick' to 'reword' for the commit

13. Lost Work After Hard Reset

Problem: Accidentally did git reset --hard and lost changes.

# Check reflog for lost commits

git reflog

# Reset to previous state

git reset --hard HEAD@{1}

# Or use specific commit hash from reflog

๐Ÿ“ Reflog is Your Friend: Git keeps a reflog of all HEAD movements for 30-90 days. It's your safety net for recovering "lost" work!

14. Merge Creating Too Many Conflicts

Problem: Merge has dozens of conflicts, overwhelming to resolve.

# Abort and try different strategy

git merge --abort

# Option 1: Use theirs/ours for specific files

git checkout --theirs file.txt

# Accept their version

git checkout --ours file.txt

# Keep your version

# Option 2: Try rebase instead

git rebase main

# Conflicts appear one commit at a time

15. Pushed Secret/Password to GitHub

Problem: Accidentally committed API keys or passwords.

# Step 1: IMMEDIATELY rotate/invalidate the secret

Change password, regenerate API key, etc.

# Step 2: Remove from history

git filter-branch --force --index-filter \ 'git rm --cached --ignore-unmatch path/to/file' \ --prune-empty --tag-name-filter cat -- --all

# Step 3: Force push

git push origin --force --all
โš ๏ธ Critical Security Note: Once pushed to GitHub, consider the secret compromised forever. Someone may have already cloned it. ALWAYS rotate credentials immediately!

Diagnostic Commands

When you're stuck, these commands help diagnose issues:

git status

# Current state overview

git log --oneline --graph --all

# Visual commit history

git reflog

# History of HEAD movements

git remote -v

# Check remote connections

git branch -vv

# Branch tracking status

git diff

# See unstaged changes

git diff --staged

# See staged changes

Prevention Tips

๐Ÿ’ก Avoid Problems Before They Happen:
  • Commit often - Small, frequent commits are easier to manage
  • Pull before push - Always sync before pushing your work
  • Use branches - Never work directly on main
  • Check before committing - Run git status and git diff
  • Use .gitignore - Prevent sensitive files from being tracked
  • Test before merging - Make sure code works before merging to main
  • Backup important work - Push to remote regularly

Emergency Commands

โš ๏ธ NUCLEAR OPTIONS - Use with extreme caution!

# Discard ALL local changes

git reset --hard HEAD

# Match local to remote exactly

git reset --hard origin/main

# Start fresh (keeps uncommitted files)

rm -rf .git git init git remote add origin URL
๐Ÿ“ When All Else Fails: Don't be afraid to ask for help! Post on Stack Overflow, check Git documentation, or ask a colleague. Git issues are common and usually solvable!
Lesson 10 of 11

Best Practices

Write Quality Code

Following Git best practices makes collaboration smoother and keeps your project maintainable!

๐Ÿ’ก Core Principle: Git should tell a clear story of your project's evolution. Every commit, branch, and merge should make that story easier to understand.

1. Commit Message Guidelines

Good commit messages are crucial for understanding project history.

The Perfect Commit Message

# Format:

type(scope): Short summary (50 chars or less) Detailed explanation of what and why (not how). Wrap at 72 characters. - Bullet points are okay - Use imperative mood: "Add feature" not "Added feature" Fixes #123

Commit Types

feat: Add user authentication system

# New feature for users

fix: Resolve memory leak in image processor

# Bug fix

docs: Update API documentation

# Documentation only

style: Format code with prettier

# Code style/formatting

refactor: Simplify database query logic

# Code restructure, no functionality change

test: Add unit tests for payment module

# Adding tests

chore: Update dependencies

# Maintenance tasks

perf: Optimize image loading speed

# Performance improvements

๐Ÿ“ Good vs Bad Commits:
โŒ "Fixed stuff"
โŒ "WIP"
โŒ "Updated files"
โœ… "fix(auth): Resolve token expiration edge case"
โœ… "feat(ui): Add dark mode toggle to settings"
โœ… "refactor(api): Extract validation logic into middleware"

2. When to Commit

Commit frequency and size matter!

๐Ÿ’ก The Golden Rules:
  • Commit early, commit often - Small, logical units
  • One logical change per commit - Don't mix refactoring with new features
  • Commit working code - Tests should pass
  • Commit before switching tasks - Clean context switching

# Good: Atomic commits

git add auth/login.js git commit -m "feat(auth): Add login form validation" git add auth/api.js git commit -m "feat(auth): Implement login API endpoint" git add tests/auth.test.js git commit -m "test(auth): Add login flow tests"

# Bad: One huge commit

git add . git commit -m "Added login stuff"

3. Branching Strategy

Consistent branch naming prevents confusion.

Branch Naming Convention

git checkout -b feature/user-dashboard

# New feature

git checkout -b fix/navbar-alignment

# Bug fix

git checkout -b hotfix/security-patch

# Urgent production fix

git checkout -b refactor/database-layer

# Code refactoring

git checkout -b docs/api-reference

# Documentation

git checkout -b test/payment-integration

# Testing

Branch Lifecycle

# 1. Create from updated main

git checkout main git pull origin main git checkout -b feature/new-feature

# 2. Work and commit regularly

git add . git commit -m "feat: Add feature implementation"

# 3. Keep branch updated

git fetch origin git rebase origin/main

# 4. Push and create PR

git push origin feature/new-feature

# 5. After merge, clean up

git checkout main git pull origin main git branch -d feature/new-feature

4. Never Commit These Files

Use .gitignore to prevent committing sensitive or generated files.

# .gitignore essentials

# Dependencies node_modules/ vendor/ venv/ # Environment & Secrets .env .env.local secrets.yaml *.pem *.key # Build outputs dist/ build/ *.min.js *.bundle.js # IDE & OS files .vscode/ .idea/ .DS_Store Thumbs.db # Logs & temp files *.log npm-debug.log* tmp/ temp/
โš ๏ธ Never Commit: API keys, passwords, private keys, database credentials, large binary files, or anything that can be regenerated from source code.

5. Pull Request Guidelines

Make your PRs easy to review and merge.

๐Ÿ’ก Perfect PR Checklist:
  • โœ… Clear, descriptive title
  • โœ… Detailed description explaining what and why
  • โœ… Link related issues
  • โœ… Include screenshots/GIFs for UI changes
  • โœ… Keep PR focused (one feature/fix)
  • โœ… Tests are passing
  • โœ… No merge conflicts
  • โœ… Self-review your code first
  • โœ… Request specific reviewers

PR Description Template

## What Brief description of changes ## Why Problem this solves or feature this adds ## How Technical approach taken ## Testing How to test these changes ## Screenshots (if applicable) Closes #123

6. Code Review Best Practices

Both authors and reviewers have responsibilities.

As a PR Author

๐Ÿ“ Do:
  • Keep PRs small (< 400 lines when possible)
  • Respond to feedback promptly
  • Be open to suggestions
  • Explain your reasoning when pushing back
  • Mark conversations as resolved

As a Reviewer

๐Ÿ“ Do:
  • Review within 24 hours
  • Be specific with feedback
  • Suggest improvements, don't just criticize
  • Ask questions to understand
  • Praise good code!
  • Test the changes locally when needed

# Bad review comment:

"This is wrong"

# Good review comment:

"Consider using Array.filter() here instead of a for loop. It's more readable and follows our functional programming style guide. Example: const active = users.filter(u => u.active);"

7. Protect Your Main Branch

Never break production! Set up branch protection rules.

# GitHub Branch Protection Rules to Enable:

โœ… Require pull request reviews before merging โœ… Require status checks to pass before merging โœ… Require branches to be up to date before merging โœ… Require conversation resolution before merging โœ… Include administrators (enforce for everyone) โš ๏ธ Do not allow force pushes โš ๏ธ Do not allow deletions

8. Keep History Clean

A clean Git history is easier to navigate and debug.

Before Merging to Main

# Clean up messy commits with interactive rebase

git rebase -i HEAD~5

# Squash, reorder, or reword commits

# Common rebase actions:

pick abc123 feat: Add login form squash def456 fix typo

# Combines def456 into abc123

reword ghi789 Add API endpoint

# Edit commit message

drop jkl012 WIP commit

# Remove commit entirely

Merge Strategies

# Option 1: Squash and merge (cleanest)

All feature branch commits become one commit on main

โœ… Best for: Small features, individual contributors

# Option 2: Rebase and merge

Preserves individual commits, linear history

โœ… Best for: When commit history is valuable

# Option 3: Merge commit

Preserves branch history with merge commit

โœ… Best for: Large features, team collaboration

9. Documentation Standards

Your README and documentation are part of your codebase.

๐Ÿ’ก Essential README Sections:
  • Project Title & Description - What it does
  • Installation - Step-by-step setup
  • Usage - How to use it
  • Contributing - How to contribute
  • License - Legal information
  • Contact - Where to get help

# Also document:

CONTRIBUTING.md # How to contribute CODE_OF_CONDUCT.md # Community guidelines CHANGELOG.md # Version history LICENSE # Legal license .github/ # GitHub templates PULL_REQUEST_TEMPLATE.md ISSUE_TEMPLATE/

10. Security Practices

Keep your repository secure from day one.

โš ๏ธ Security Checklist:
  • โœ… Use .gitignore from the start
  • โœ… Scan commits for secrets before pushing
  • โœ… Enable GitHub's secret scanning
  • โœ… Use environment variables for config
  • โœ… Keep dependencies updated
  • โœ… Enable 2FA on GitHub account
  • โœ… Use signed commits (optional but good)
  • โœ… Review third-party actions/workflows

# Sign commits with GPG

git config --global user.signingkey YOUR_KEY_ID git config --global commit.gpgsign true git commit -S -m "feat: Signed commit"

11. Team Collaboration

Make working together seamless.

๐Ÿ’ก Team Git Standards:
  • Agree on workflow - Everyone uses same strategy
  • Document conventions - Write them down
  • Use consistent formatting - Setup Prettier/ESLint
  • Communicate in commits/PRs - Don't use Slack for code discussions
  • Regular sync meetings - Prevent merge conflicts
  • Share knowledge - Review each other's code

12. Performance & Efficiency

Keep your repository fast and manageable.

# Check repository size

du -sh .git

# Clean up unnecessary files

git gc --aggressive --prune=now

# Use Git LFS for large files

git lfs track "*.psd" git lfs track "*.mp4"

# Shallow clone for CI/CD

git clone --depth 1 URL

# Faster clones in pipelines

Common Anti-Patterns to Avoid

โš ๏ธ Don't Do These:
  • โŒ Committing directly to main branch
  • โŒ Force pushing to shared branches
  • โŒ Huge commits with mixed changes
  • โŒ Meaningless commit messages
  • โŒ Committing broken code
  • โŒ Not pulling before pushing
  • โŒ Leaving dead code/commented code
  • โŒ Not using branches for features
  • โŒ Ignoring merge conflicts
  • โŒ Rewriting public history

Quick Win Checklist

๐Ÿ’ก Start These Today:
  • โœ… Create a comprehensive .gitignore
  • โœ… Write better commit messages
  • โœ… Use branches for all changes
  • โœ… Set up branch protection rules
  • โœ… Pull before you push
  • โœ… Review your own PRs first
  • โœ… Keep PRs small and focused
  • โœ… Document as you code
๐Ÿ“ Remember: Best practices evolve with your team and project. Start with these fundamentals, then adapt based on what works best for your workflow!
Lesson 11 of 11

Quick Reference

Git Commands Cheat Sheet

Your go-to reference for all essential Git commands. Bookmark this page!

๐Ÿ’ก Pro Tip: Press Ctrl+F (or Cmd+F on Mac) to quickly search for a specific command!

๐Ÿš€ Getting Started

git config --global user.name "Your Name"

# Set your name

git config --global user.email "email@example.com"

# Set your email

git config --list

# View all settings

git --version

# Check Git version

git help <command>

# Get help for any command

๐Ÿ“ฆ Creating Repositories

git init

# Initialize new repository

git init <directory>

# Create repo in specific directory

git clone <url>

# Clone remote repository

git clone <url> <directory>

# Clone into specific directory

git clone --depth 1 <url>

# Shallow clone (faster)

๐Ÿ“ Basic Commands

git status

# Check repository status

git add <file>

# Stage specific file

git add .

# Stage all changes

git add -p

# Stage changes interactively

git commit -m "message"

# Commit staged changes

git commit -am "message"

# Stage and commit tracked files

git commit --amend

# Modify last commit

git commit --amend --no-edit

# Add to last commit, keep message

๐Ÿ” Viewing History

git log

# View commit history

git log --oneline

# Compact history view

git log --graph --all

# Visual branch history

git log -p

# Show changes in each commit

git log --author="Name"

# Filter by author

git log --since="2 weeks ago"

# Time-based filter

git log --grep="keyword"

# Search commit messages

git show <commit>

# Show specific commit details

git blame <file>

# See who changed each line

๐Ÿ”„ Undoing Changes

git restore <file>

# Discard changes in working directory

git restore --staged <file>

# Unstage file

git reset HEAD~1

# Undo last commit, keep changes

git reset --soft HEAD~1

# Undo commit, keep staged

git reset --hard HEAD~1

# Undo commit, discard changes โš ๏ธ

git revert <commit>

# Create new commit that undoes changes

git clean -fd

# Remove untracked files โš ๏ธ

๐ŸŒฟ Branching

git branch

# List all branches

git branch -a

# List all branches (including remote)

git branch <branch-name>

# Create new branch

git branch -d <branch>

# Delete branch (safe)

git branch -D <branch>

# Force delete branch

git branch -m <old> <new>

# Rename branch

git checkout <branch>

# Switch to branch

git checkout -b <branch>

# Create and switch to branch

git switch <branch>

# Switch to branch (modern)

git switch -c <branch>

# Create and switch (modern)

๐Ÿ”€ Merging & Rebasing

git merge <branch>

# Merge branch into current branch

git merge --no-ff <branch>

# Merge with merge commit

git merge --squash <branch>

# Merge and squash commits

git merge --abort

# Cancel merge

git rebase <branch>

# Rebase current branch

git rebase -i HEAD~3

# Interactive rebase last 3 commits

git rebase --continue

# Continue after resolving conflicts

git rebase --abort

# Cancel rebase

๐ŸŒ Remote Repositories

git remote -v

# List remote connections

git remote add <name> <url>

# Add new remote

git remote remove <name>

# Remove remote

git remote rename <old> <new>

# Rename remote

git remote set-url origin <url>

# Change remote URL

git fetch

# Download remote changes

git fetch --all

# Fetch from all remotes

git fetch --prune

# Remove deleted remote branches

git pull

# Fetch and merge

git pull --rebase

# Fetch and rebase

git push

# Push commits to remote

git push -u origin <branch>

# Push and set upstream

git push --force

# Force push โš ๏ธ Dangerous!

git push --force-with-lease

# Safer force push

git push origin --delete <branch>

# Delete remote branch

๐Ÿ“ฆ Stashing

git stash

# Save changes temporarily

git stash save "message"

# Stash with description

git stash list

# List all stashes

git stash pop

# Apply and remove latest stash

git stash apply

# Apply stash without removing

git stash apply stash@{2}

# Apply specific stash

git stash drop

# Delete latest stash

git stash clear

# Delete all stashes

git stash show

# Show stash changes

๐Ÿ” Comparing Changes

git diff

# Show unstaged changes

git diff --staged

# Show staged changes

git diff <branch1> <branch2>

# Compare two branches

git diff <commit1> <commit2>

# Compare two commits

git diff HEAD~1 HEAD

# Compare with previous commit

git diff --stat

# Show diff statistics

git diff <file>

# Show changes in specific file

๐Ÿท๏ธ Tags

git tag

# List all tags

git tag <tagname>

# Create lightweight tag

git tag -a v1.0 -m "Version 1.0"

# Create annotated tag

git tag <tagname> <commit>

# Tag specific commit

git tag -d <tagname>

# Delete local tag

git push origin <tagname>

# Push tag to remote

git push origin --tags

# Push all tags

git push origin --delete <tagname>

# Delete remote tag

git show <tagname>

# Show tag details

๐Ÿ”Ž Advanced Commands

git cherry-pick <commit>

# Apply specific commit to current branch

git reflog

# Show history of HEAD movements

git reflog show <branch>

# Show reflog for specific branch

git bisect start

# Start binary search for bug

git bisect bad

# Mark current commit as bad

git bisect good <commit>

# Mark commit as good

git grep "pattern"

# Search for pattern in files

git shortlog -sn

# Count commits per author

git archive --format=zip HEAD > project.zip

# Export repository as zip

๐Ÿ”ง Configuration

git config --global core.editor "code --wait"

# Set default editor to VS Code

git config --global init.defaultBranch main

# Set default branch name

git config --global pull.rebase true

# Always rebase on pull

git config --global alias.st status

# Create alias (git st)

git config --global alias.co checkout

# Alias for checkout

git config --global alias.br branch

# Alias for branch

git config --global alias.cm "commit -m"

# Alias for commit

git config --global color.ui auto

# Enable colored output

๐Ÿงน Maintenance

git gc

# Clean up unnecessary files

git gc --aggressive

# More thorough cleanup

git fsck

# Verify repository integrity

git prune

# Remove unreachable objects

git count-objects -vH

# Show repository size

๐Ÿ™ GitHub CLI (gh)

gh auth login

# Authenticate with GitHub

gh repo create

# Create new repository

gh repo clone <repo>

# Clone repository

gh pr create

# Create pull request

gh pr list

# List pull requests

gh pr view

# View PR details

gh pr checkout <number>

# Check out PR locally

gh issue create

# Create new issue

gh issue list

# List issues

gh workflow view

# View GitHub Actions workflows

๐Ÿ“‹ Common Scenarios

Scenario 1: Undo Last Commit (Keep Changes)

git reset --soft HEAD~1

# Undo commit, keep changes staged

Scenario 2: Change Last Commit Message

git commit --amend -m "New message"

Scenario 3: Discard All Local Changes

git reset --hard HEAD git clean -fd

Scenario 4: Create Branch from Remote

git fetch origin git checkout -b local-branch origin/remote-branch

Scenario 5: Sync Fork with Upstream

git remote add upstream <original-repo-url> git fetch upstream git checkout main git merge upstream/main git push origin main

Scenario 6: Squash Last 3 Commits

git rebase -i HEAD~3

# Change 'pick' to 'squash' for commits to combine

Scenario 7: Find Commit That Introduced Bug

git bisect start git bisect bad

# Current commit is bad

git bisect good v1.0

# v1.0 was good

# Test each commit, mark as good/bad

git bisect good/bad git bisect reset

# When done

Scenario 8: Move Commits to New Branch

git branch new-branch git reset --hard HEAD~3

# Remove last 3 commits from current branch

git checkout new-branch

# Commits are now on new-branch

โš ๏ธ Dangerous Commands (Use Carefully!)

These commands can cause data loss:
  • git reset --hard - Discards all changes
  • git clean -fd - Removes untracked files
  • git push --force - Overwrites remote history
  • git branch -D - Force deletes branch
  • git reflog expire - Removes reflog entries

๐Ÿ“š Useful Git Aliases

Add these to your ~/.gitconfig file:

[alias] st = status co = checkout br = branch cm = commit -m lg = log --oneline --graph --all last = log -1 HEAD unstage = reset HEAD -- undo = reset --soft HEAD~1 amend = commit --amend --no-edit cleanup = !git branch --merged | grep -v 'main' | xargs git branch -d

๐ŸŽฏ Quick Tips

๐Ÿ’ก Remember:
  • Commit often - Small commits are easier to manage
  • Pull before push - Avoid conflicts
  • Use branches - Never work directly on main
  • Write good messages - Your future self will thank you
  • Check status - Always know what you're committing
  • Use .gitignore - Don't commit unnecessary files
  • Learn reflog - It's your safety net

๐ŸŽ‰ Congratulations!

๐Ÿ“ You've Completed the Tutorial!

You now have all the essential Git knowledge to work effectively with version control. Bookmark this page for quick reference, and remember: the best way to learn Git is by using it daily. Keep practicing, and you'll become a Git expert in no time!

Next Steps:
  • Create your own projects and push them to GitHub
  • Contribute to open-source projects
  • Explore advanced topics like Git hooks and submodules
  • Share your knowledge with others!