The Complete GitHub Guide: From Zero to Advanced (Built for Beginners, Trusted by Pros)
Welcome. If you’re reading this, you’re about to unlock one of the most powerful tools in software development. GitHub isn’t just a “code storage” website. It’s a collaboration engine, a version time-machine, and a launchpad for everything from school projects to enterprise software.
Let’s build your GitHub mastery from the ground up.
🟢 PHASE 1: THE ABSOLUTE BASICS (Account → First Push)
Step 1: Create a GitHub Account
Why it matters: GitHub is your public developer portfolio. Everything you build here becomes visible to schools, employers, and open-source communities.
Go to https://github.com
Click Sign up (top right)
Enter your email, create a strong password, and pick a username (make it professional: yourname-dev or firstnamelastname)
Verify your email (GitHub will send a confirmation link)
Skip the paid plan prompt. The Free tier gives you unlimited public/private repos, Actions minutes, and GitHub Pages.
✅ Pro Tip: Use a personal email you’ll keep forever. School emails expire.
Step 2: Install Git on Your Computer
What is Git? Git is the engine that tracks every change to your files. GitHub is the website that hosts those tracked files. You need Git installed locally to talk to GitHub.
Visit https://git-scm.com/downloads
Download the installer for your OS:
Windows: .exe (choose default settings, but check “Add Git to PATH”)
macOS: .dmg or use Homebrew: brew install git
Linux: sudo apt install git (Debian/Ubuntu) or sudo dnf install git (Fedora)
Run the installer. Keep all defaults unless you know exactly what you’re changing.
Verify installation:
Open Terminal (macOS/Linux) or Command Prompt/PowerShell (Windows) and run:git --version
You should see git version 2.xx.x (2.40+ is fine).
✅ 8th Grade Analogy: Think of Git as a “save game” system for your files. GitHub is the cloud where you upload those save files so others can play or download them.
Step 3: Configure Your Identity
Git needs to know who you are before it records changes.
Run these two commands (replace with your actual name and GitHub email):git config --global user.name "Your Real Name" git config --global user.email "your-email@example.com"
Verify:git config --list
You’ll see user.name and user.email in the output.
⚠️ Warning: Use the same email you registered with on GitHub. Otherwise, your commits won’t show your profile picture or link to your account.
Step 4: Create Your First Repository (Repo)
A repository is a folder that Git tracks. “Repo” is short for repository.
Log into GitHub
Click the + icon (top right) → New repository
Fill in:
Repository name: my-first-project (lowercase, hyphens instead of spaces)
Description: Optional but recommended. Example: Learning GitHub basics
Visibility: Public (anyone can see it) or Private (only you and collaborators)
✅ Check Add a README file
✅ Leave other defaults for now
Click Create repository
You now have a live repo at https://github.com/your-username/my-first-project
Step 5: The Core Workflow (Clone → Edit → Add → Commit → Push)
This is the heartbeat of GitHub. Memorize it. Live it.
1. Clone (Download) the Repo to Your Computer
Open your terminal and navigate to where you want the folder:cd ~/Documents # macOS/Linux cd %USERPROFILE%\Documents # Windows
Clone the repo:git clone https://github.com/YOUR-USERNAME/my-first-project.git cd my-first-project
You now have a local copy. The README.md is inside.
2. Edit Files
Open the folder in any text editor (VS Code, Notepad++, Sublime, etc.).
Create a new file called hello.txt and write:Hello GitHub! I’m learning version control.
Save it.
3. Add (Stage) the Changes
Git doesn’t track files automatically. You must tell it what to save.git add hello.txt
To stage everything in the folder:git add .
4. Commit (Save a Snapshot)
A commit is a labeled snapshot of your staged files.git commit -m "Add hello.txt with welcome message"
📝 Commit Message Rule: Start with a verb, keep it under 50 characters, explain what changed, not why. Good: Fix typo in README. Bad: stuff.
5. Push (Upload to GitHub)git push origin mainorigin = your GitHub repomain = the default branch name (GitHub changed from master to main in 2020)
✅ Check it: Refresh your GitHub repo page. You’ll see hello.txt and your commit message.
🔁 The Loop: edit → add → commit → push is how 99% of your work will flow.
🟡 PHASE 2: INTERMEDIATE WORKFLOW (Branches, PRs & Collaboration)
Step 6: Understand Branches (The “What-If” Sandbox)
Why branches? You never edit main directly in professional work. Branches let you experiment without breaking the working code.
Think of main as your finished homework. A branch is a draft copy. You can mess up the draft, fix it, then merge it into the final version.
Create a branch:git checkout -b feature/add-about-sectioncheckout -b = create + switch to new branch
Branch name format: category/description (e.g., fix/login-bug, docs/update-readme)
Verify:git branch
You’ll see * feature/add-about-section (the * means you’re on it).
Step 7: Work, Commit, and Push on Your Branch
Edit files on this branch. Stage and commit:git add . git commit -m "Add about section with project goals"
Push the branch to GitHub:git push -u origin feature/add-about-section
The -u flag links your local branch to the remote one. Future pushes can just use git push.
Step 8: Pull Requests (PRs) Explained
A Pull Request is GitHub’s formal way of saying: “I finished my changes on a branch. Please review and merge them into main.”
Go to your GitHub repo page
You’ll see a yellow banner: feature/add-about-section had recent pushes. Compare & pull request
Click Compare & pull request
Fill in:
Title: Add about section to README
Description: Explain what you changed, why, and how to test it.
✅ Assign reviewers (optional for solo projects)
✅ Check Allow edits by maintainers
Click Create pull request
GitHub will now run automatic checks (if configured). If everything passes, click Merge pull request → Confirm merge.
✅ Pro Tip: Always delete the branch after merging (GitHub offers a button: Delete branch). It keeps your repo clean.
Step 9: Syncing & The .gitignore File
Keep Local & Remote in Sync
Before starting work, always pull the latest changes:git checkout main git pull origin main
If you’re on a branch:git pull origin main
This fetches main updates and merges them into your current branch.
The .gitignore File
Some files should never be tracked: passwords, temporary files, OS caches, node_modules/, .env.
Create a file named .gitignore (note the dot at the start)
Add patterns:# OS files .DS_Store Thumbs.db # Node.js node_modules/ .env # Python __pycache__/ *.pyc venv/
Commit it:git add .gitignore git commit -m "Add gitignore to exclude sensitive/temp files" git push
⚠️ Warning: Once a file is tracked, adding it to .gitignore won’t stop Git from tracking it. Remove it first:git rm --cached filename git commit -m "Stop tracking filename"
Step 10: Authentication (SSH vs HTTPS)
Typing your password every push is annoying. Set up SSH or use GitHub CLI.
Option A: SSH (Recommended for long-term use)
Generate a key:ssh-keygen -t ed25519 -C "your-email@example.com"
Press Enter for all prompts (use default path, no passphrase for beginners).
Copy the public key:
macOS/Linux: cat ~/.ssh/id_ed25519.pub
Windows: type %USERPROFILE%\.ssh\id_ed25519.pub
Go to GitHub → Settings → SSH and GPG keys → New SSH key
Title: My Laptop
Paste the key
Click Add SSH key
Clone repos using SSH URL instead of HTTPS:git clone git@github.com:your-username/repo.git
Option B: GitHub CLI (Modern & Easy)
Install: brew install gh (macOS), winget install GitHub.cli (Windows), or sudo apt install gh (Linux)
Login:gh auth login
Follow prompts (HTTPS + browser paste is easiest)
Now git push works without passwords.
🟠 PHASE 3: ADVANCED GITHUB (Automation, Security & Pro Workflows)
Step 11: Master the GitHub CLI (gh)
The GitHub CLI lets you control GitHub from your terminal—no browser needed. It’s faster, scriptable, and pro-level.
Install gh:
macOS: brew install gh
Windows: winget install GitHub.cli or download from https://cli.github.com
Linux: sudo apt install gh (Debian/Ubuntu) or follow distro-specific instructions
Authenticate:gh auth login
Follow prompts:
Choose GitHub.com
Choose HTTPS or SSH (match your Git setup)
Choose Login with a web browser
Copy the one-time code, press Enter, paste code in browser, authorize
Verify:gh repo list
You’ll see your repos listed in terminal.
Common gh Commands:# Create a new repo gh repo create my-new-project --public --clone # View your PRs gh pr list # Create a PR from current branch gh pr create --title "Fix: update login validation" --body "Added email format check" # Review a PR (comment, approve, request changes) gh pr review 123 --approve -b "Looks good! ✅" # Clone a repo by URL gh repo clone username/repo-name # View repo stats gh repo view --web
✅ 8th Grade Analogy: gh is like giving GitHub a remote control. Instead of clicking buttons on a website, you type short commands to do the same thing—faster.
Step 12: GitHub Actions (Automate Everything)
What are Actions? GitHub Actions are automated workflows that run when you push code, open a PR, or on a schedule. Think: auto-test your code, deploy your website, send notifications.
Real-world examples:
Run tests on every push → block merge if tests fail
Auto-deploy to GitHub Pages when main updates
Send a Slack message when a new issue is opened
Create Your First Workflow
In your repo, create folder: .github/workflows/
Inside, create file: ci.yml
Paste this beginner-friendly workflow:name: Run Tests on Push on: [push, pull_request] jobs: test: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v4 - name: Set up Node.js uses: actions/setup-node@v4 with: node-version: '20' - name: Install dependencies run: npm ci - name: Run tests run: npm test
Commit and push:git add .github/workflows/ci.yml git commit -m "Add GitHub Actions workflow for testing" git push
✅ Watch it run: Go to your repo → Actions tab. You’ll see the workflow running in real-time with green checkmarks or red Xs.
🔧 Customize: Change npm test to python -m pytest, phpunit, or any command. Actions support Docker, AWS, Azure, and 20,000+ community actions.
📚 Learn more: https://docs.github.com/en/actions
Step 13: GitHub Pages (Free Hosting for Websites)
What is GitHub Pages? Free static site hosting directly from your GitHub repo. Perfect for portfolios, project demos, documentation, or class assignments.
Deploy a Simple Site in 3 Steps
Create a repo named your-username.github.io (exactly—replace your-username)
Example: If your username is coder123, repo name = coder123.github.io
Add an index.html file:<!DOCTYPE html> <html> <head><title>My Site</title></head> <body><h1>Hello from GitHub Pages! 🚀</h1></body> </html>
Enable Pages:
Repo → Settings → Pages (left sidebar)
Under Build and deployment → Source: Choose Deploy from a branch
Branch: main → Folder: / (root) → Save
✅ Live in 60 seconds: Visit https://your-username.github.io
Advanced: Deploy from /docs or a Branch
For project sites (not user sites), you can deploy from /docs folder or a gh-pages branch.
Works great with static site generators: Jekyll (built-in), Hugo, Eleventy, Vite, etc.
⚠️ Limitations: GitHub Pages hosts static sites only (HTML, CSS, JS). No PHP, Python, or databases. For dynamic apps, use Vercel, Netlify, or Render.
Step 14: Advanced Branching Strategies (Merge vs Rebase)
Merge: The Safe, Visible Pathgit checkout main git merge feature/add-search git push origin main
Creates a “merge commit” showing the branch history
Preserves full context: who did what, when
Best for: team projects, audit trails, public repos
Rebase: The Clean, Linear Historygit checkout feature/add-search git rebase main # Fix any conflicts if prompted git push --force-with-lease # ⚠️ Only on your own branches
Rewrites history to look like work happened in a straight line
Cleaner git log, but never rebase shared/public branches
Best for: personal projects, pre-PR cleanup
✅ 8th Grade Rule:
Use merge when working with others (like group homework).
Use rebase when cleaning up your own draft before showing it (like editing your essay before turning it in).
Pro Strategy: Git Flow (Simplified)main → production-ready code (always stable) develop → integration branch for features feature/* → new work (e.g., feature/user-login) release/* → prep for launch (testing, version bump) hotfix/* → urgent fixes to main
Use git flow CLI tool or manage manually. Most startups use a simplified version: main + feature/* + PRs.
Step 15: Security & Best Practices (Don’t Skip This)
🔐 Protect Your Main Branch
Repo → Settings → Branches → Add branch protection rule
Branch name pattern: main
Check:
✅ Require a pull request before merging
✅ Require approvals (1 or 2)
✅ Require status checks to pass (e.g., your GitHub Actions)
✅ Include administrators (yes, even you)
Click Create
Now no one—not even you—can push directly to main. All changes require review.
🕵️ Scan for Secrets (Passwords, API Keys)
GitHub auto-scans for leaked secrets, but prevent leaks first:
Use .gitignore for .env, config.php, secrets.json
Use GitHub Secrets for Actions:
Repo → Settings → Secrets and variables → Actions
Add API_KEY, DEPLOY_TOKEN, etc.
Use in workflow: ${{ secrets.API_KEY }}
Install pre-commit hooks to block accidental commits:# Install pre-commit framework pip install pre-commit # Create .pre-commit-config.yaml echo "repos: - repo: https://github.com/gitleaks/gitleaks rev: v8.16.3 hooks: - id: gitleaks" > .pre-commit-config.yaml pre-commit install
Now git commit auto-scans for passwords before saving.
🛡️ Enable Two-Factor Authentication (2FA) on GitHub
GitHub → Settings → Password and authentication
Under Two-factor authentication, click Enable 2FA
Choose: Authenticator app (Google Authenticator, Authy) or SMS
Save backup codes somewhere safe
⚠️ Warning: GitHub will soon require 2FA for all active contributors. Enable it now.
Step 16: Pro Workflow Checklist (Daily Use)
Before you code:git checkout main git pull origin main git checkout -b feature/your-task-name
While coding:git add . git commit -m "Feat: add user profile upload" # Repeat as needed
Before pushing:git fetch origin git rebase origin/main # or merge, per team rules # Resolve conflicts if any git push -u origin feature/your-task-name
After PR is merged:git checkout main git pull origin main git branch -d feature/your-task-name # delete local git push origin --delete feature/your-task-name # delete remote (or use GitHub UI)
✅ Bonus: Aliases for Speed (add to ~/.gitconfig):[alias] co = checkout br = branch ci = commit st = status lg = log --oneline --graph --all unstage = reset HEAD -- last = log -1 HEAD
Now git st = git status, git lg = pretty log view.
Step 17: Debugging & Recovery (When Things Break)
Undo a Commit (Before Push)git reset --soft HEAD~1 # undo commit, keep changes staged git reset --mixed HEAD~1 # undo commit, unstage changes (default) git reset --hard HEAD~1 # ⚠️ DANGER: deletes commit AND changes
Undo a Push (If You’re the Only One Using the Branch)git reset --hard HEAD~1 git push --force-with-lease # never use --force on shared branches
Recover a Deleted Branchgit reflog # shows all recent actions # Find the commit hash before deletion git checkout -b recovered-branch abc1234
Resolve Merge Conflicts
When Git says CONFLICT (content): Merge conflict in file.txt:
Open file.txt. Look for:<<<<<<< HEAD Your current changes ======= Incoming changes from main >>>>>>> main
Edit to keep what you want, delete the markers
Stage and commit:git add file.txt git commit -m "Resolve merge conflict in file.txt"
✅ 8th Grade Tip: Conflicts are like two people editing the same sentence. Git asks: “Which version do you want to keep?” You decide.
Step 18: Level Up: Contributing to Open Source
GitHub’s superpower: collaborating with strangers on real software.
How to Contribute (Step-by-Step)
Find a beginner-friendly repo:
Search good-first-issue label: https://github.com/search?q=label%3Agood-first-issue
Try: firstcontributions/first-contributions
Fork the repo (click Fork button on GitHub)
Clone your fork:git clone https://github.com/YOUR-USERNAME/repo-name.git cd repo-name
Add the original repo as upstream:git remote add upstream https://github.com/original-owner/repo-name.git git fetch upstream
Create branch, make changes, commit, push to your fork
Open a PR from your fork to the original repo
Respond to review comments, push fixes, celebrate when merged 🎉
✅ First PR Template: Use this commit message format:docs: add my name to contributors list Signed-off-by: Your Name <your-email@example.com>
🎯 FINAL CHECKLIST: GitHub Mastery in 10 Points
✅ Account created + 2FA enabled
✅ Git installed + identity configured
✅ SSH or CLI auth set up (no password prompts)
✅ .gitignore in every repo
✅ Branch for every feature (feature/description)
✅ PRs for all merges into main
✅ GitHub Actions for auto-test/deploy
✅ Branch protection on main
✅ Secrets stored in GitHub, not code
✅ Contributed to at least 1 open-source repo
📚 Recommended Next Steps
Practice Repo: Create github-practice and try every command above
Cheat Sheet: Print https://training.github.com/downloads/github-git-cheat-sheet.pdf
Interactive Learning: https://learngitbranching.js.org (visual Git simulator)
Advanced Reading:
Pro Git Book (free): https://git-scm.com/book/en/v2
GitHub Docs: https://docs.github.com
Portfolio: Turn your username.github.io into a real portfolio with projects, resume, contact form
💡 Remember: GitHub is a skill, not a tool. You don’t master it by reading—you master it by doing. Break things. Fix them. Push. Learn. Repeat.
You now have the complete roadmap—from “What is a repo?” to shipping production code with automated tests, secure secrets, and team workflows.
Your turn:
👉 Create a repo right now.
👉 Make one commit.
👉 Push it.
👉 Come back and level up.
Need a specific deep-dive next? Ask for:
“GitHub for WordPress developers”
“GitHub Actions for PHP/MySQL apps”
“How to use GitHub with VS Code + Live Share”
“Advanced rebase/interactive workflows”
Happy coding. 🚀
GitHub Commands Step by Step
Step 1 | Git Initialize
Command (to initialize a git repo): git init
When to use: Initialize a new Git repository in your local project folder. Run this once when starting version control for a new project.
Step 2 | Add Single File or Multiple Files
Command (for single file): git add filename.txt
Command (for multiple specific files): git add file1.txt file2.txt
Command (for all files): git add .
When to use: Stage changes you want to include in your next commit. Use git add . to stage all modified/new files, or specify files to be selective.
Step 3 | Git Commit
Command (commit with message): git commit -m "Your descriptive message here"
Command (commit with longer message): git commit -m "Title" -m "Detailed description of changes"
When to use: Save a snapshot of your staged changes to the local repository. Always write clear, concise messages explaining WHAT changed.
Step 4 | Check Repository Status
Command: git status
When to use: See which files are modified, staged, or untracked. Run this frequently to understand your repo’s current state before adding or committing.
Step 5 | View Commit History
Command (simple log): git log
Command (one-line compact log): git log --oneline
Command (graph view): git log --graph --oneline --all
When to use: Review past commits, find commit hashes, or understand the project’s change history.
Step 6 | Create a New Branch
Command: git branch branch-name
Command (create + switch): git checkout -b branch-name OR git switch -c branch-name
When to use: Start working on a new feature, bug fix, or experiment without affecting the main codebase.
Step 7 | List All Branches
Command (local branches): git branch
Command (all branches including remote): git branch -a
When to use: See which branches exist locally or remotely. The * symbol shows your current branch.
Step 8 | Switch Between Branches
Command: git checkout branch-name OR git switch branch-name
When to use: Move your working directory to a different branch to work on or review its code.
Step 9 | Rename Current Branch
Command: git branch -m new-branch-name
When to use: Fix a typo or update a branch name for clarity (e.g., changing fix-bug to fix/login-error).
Step 10 | Delete a Branch
Command (safe delete): git branch -d branch-name
Command (force delete): git branch -D branch-name
When to use: Remove a branch after merging or when abandoning a feature. -d prevents deleting unmerged work; -D forces deletion.
Step 11 | Connect Local Repo to GitHub (Set Remote Origin)
Command: git remote add origin https://github.com/username/repository-name.git
When to use: Link your local repository to a remote GitHub repository for the first time. Replace with your actual repo URL.
Step 12 | Verify Remote Connections
Command: git remote -v
When to use: Check which remote repositories (origin, upstream, etc.) your local repo is connected to and their URLs.
Step 13 | Push Local Branch to GitHub
Command (first push with tracking): git push -u origin branch-name
Command (subsequent pushes): git push
When to use: Upload your local commits to GitHub. The -u flag sets upstream tracking so future pushes are simpler.
Step 14 | Pull Updates from GitHub
Command: git pull origin branch-name
Command (with rebase): git pull --rebase origin branch-name
When to use: Fetch and merge changes from GitHub into your local branch. Use before starting work to stay synced with teammates.
Step 15 | Clone a Remote Repository
Command: git clone https://github.com/username/repository-name.git
Command (clone into custom folder): git clone https://github.com/username/repo.git folder-name
When to use: Download a complete copy of a GitHub repository to your local machine for the first time.
Step 16 | Fetch Remote Changes (Without Merging)
Command: git fetch origin
When to use: Download updates from GitHub without automatically merging them. Useful for reviewing changes before integrating.
Step 17 | Merge One Branch into Another
Command:git checkout main git merge branch-name
When to use: Combine changes from a feature branch into your main branch. Do this after testing and via Pull Request on GitHub.
Step 18 | Resolve Merge Conflicts
Commands:
Open conflicted files and look for <<<<<<<, =======, >>>>>>>
Edit to keep desired code, remove markers
Stage resolved files: git add filename
Complete merge: git commit
When to use: When Git can’t automatically merge changes (e.g., same line edited in two branches). Manual resolution required.
Step 19 | Stash Temporary Changes
Command (save changes): git stash
Command (save with message): git stash push -m "Work in progress"
Command (view stashes): git stash list
Command (apply latest stash): git stash pop
When to use: Temporarily save uncommitted work to switch branches or pull updates, then restore later.
Step 20 | View Differences (Diff)
Command (unstaged changes): git diff
Command (staged changes): git diff --staged
Command (between branches): git diff branch1..branch2
When to use: See exactly what lines changed before committing or merging. Great for code review.
Step 21 | Undo Changes (Before Commit)
Command (unstage file): git reset filename
Command (discard local edits): git checkout -- filename OR git restore filename
When to use: You staged a file by mistake or want to revert uncommitted changes to the last saved version.
Step 22 | Undo Last Commit (Keep Changes)
Command: git reset --soft HEAD~1
When to use: You committed too early or with a bad message. This undoes the commit but keeps your changes staged.
Step 23 | Undo Last Commit (Discard Changes)
Command: git reset --hard HEAD~1
⚠️ Warning: This permanently deletes the last commit AND all changes. Use only if you’re 100% sure.
When to use: You made a commit with broken code and want to completely erase it from history (only on local/private branches).
Step 24 | Revert a Public Commit (Safe Undo)
Command: git revert commit-hash
When to use: Undo a commit that’s already been pushed to GitHub. Creates a NEW commit that reverses the changes (safe for shared branches).
Step 25 | Configure Git User Info
Commands:git config --global user.name "Your Name" git config --global user.email "your-email@example.com"
When to use: Set your identity for commits. Run once per machine. Use --global for all repos, or remove it for repo-specific settings.
Step 26 | Set Default Branch Name
Command: git config --global init.defaultBranch main
When to use: Ensure new repos use main instead of master as the default branch (GitHub’s standard since 2020).
Step 27 | Create and Use .gitignore
Command (create file): Create a file named .gitignore in your project root
Example content:node_modules/ .env *.log .DS_Store
When to use: Tell Git which files/folders to ignore (e.g., secrets, dependencies, OS files). Commit this file so teammates share the same rules.
Step 28 | Remove a File from Git Tracking
Command (stop tracking but keep file): git rm --cached filename
Command (delete from disk and Git): git rm filename
When to use: You added a file to .gitignore but Git still tracks it, or you want to delete a file from the repo.
Step 29 | Rename or Move a File in Git
Command: git mv old-name.txt new-name.txt
When to use: Rename or move files while preserving Git history. Better than manual rename + add.
Step 30 | Tag a Release Version
Command (lightweight tag): git tag v1.0.0
Command (annotated tag): git tag -a v1.0.0 -m "Release version 1.0.0"
Command (push tags to GitHub): git push origin --tags
When to use: Mark important milestones (releases) in your project history. Tags are immutable references like v2.1.3.
Step 31 | Update Your Forked Repository
Commands (if you forked someone else’s repo):git remote add upstream https://github.com/original-owner/repo.git git fetch upstream git checkout main git merge upstream/main git push origin main
When to use: Keep your fork synced with the original project you forked from. Essential for contributing to open source.
Step 32 | Clean Untracked Files (Use with Caution)
Command (dry run): git clean -n
Command (actually delete): git clean -f
Command (delete untracked directories too): git clean -fd
⚠️ Warning: This permanently deletes untracked files. Always run -n first to preview.
When to use: Remove temporary files, build artifacts, or other untracked clutter from your working directory.
🔄 The Daily Workflow Cheat Sheet (Memorize This)# Start your day: Get latest code git checkout main git pull origin main # Work on a new feature git checkout -b feature/your-feature-name # Edit files... # Stage and commit git add . git commit -m "Add feature: brief description" # Push to GitHub git push -u origin feature/your-feature-name # Later: Create Pull Request on GitHub website # After merge: Clean up locally git checkout main git pull origin main git branch -d feature/your-feature-name
🚨 Critical Safety Rules for Beginners
Never git push --force on shared branches (main, develop). It rewrites history and breaks teammates’ work.
Always git pull before starting work to avoid merge conflicts.
Commit small, logical changes with clear messages. One feature/fix per commit.
Test before you commit. Don’t push broken code.
Use branches for everything. Never work directly on main.
Back up important work before running reset --hard or clean -f.
Step 33 | Rebase Branch onto Main (Clean History)
Command:git checkout feature-branch git rebase main
Command (interactive rebase): git rebase -i HEAD~3
When to use: Rewrite your branch history to appear linear and clean before merging. Never rebase public/shared branches—only use on your private feature branches.
Step 34 | Abort a Rebase in Progress
Command: git rebase --abort
When to use: If conflicts during rebase become too complex or you made a mistake. This returns your branch to its pre-rebase state.
Step 35 | Continue Rebase After Resolving Conflicts
Commands:# After editing conflicted files: git add resolved-file.txt git rebase --continue
When to use: You’ve manually fixed merge conflicts during a rebase and want to proceed to the next commit.
Step 36 | Cherry-Pick a Specific Commit
Command: git cherry-pick commit-hash
Command (multiple commits): git cherry-pick commit1 commit2 commit3
When to use: Apply a single commit from another branch without merging the entire branch. Useful for hotfixes or backporting changes.
Step 37 | Bisect to Find a Bug (Binary Search)
Commands:git bisect start git bisect bad HEAD # Current version has bug git bisect good v1.0.0 # Known good version # Git checks out a middle commit; test it: git bisect good # or git bisect bad # Repeat until Git identifies the breaking commit git bisect reset # End bisect session
When to use: Track down which commit introduced a bug when you have many commits between a known-good and known-bad state.
Step 38 | Show Details of a Specific Commit
Command: git show commit-hash
Command (show only stats): git show --stat commit-hash
When to use: Inspect exactly what changed in a specific commit—files modified, lines added/removed, and the commit message.
Step 39 | Search Commit History by Keyword
Command: git log --grep="keyword"
Command (search in code changes): git log -S "functionName"
When to use: Find commits related to a feature, bug, or code change without knowing the exact commit hash.
Step 40 | Create a Patch File from Changes
Command: git format-patch -1 commit-hash
When to use: Export a commit as an email-style patch file for sharing changes outside of GitHub (e.g., mailing lists).
🟣 GITHUB-SPECIFIC WORKFLOWS (UI + CLI)
Step 41 | Create a Pull Request Template
File: .github/PULL_REQUEST_TEMPLATE.md
Example content:## Description <!-- What does this PR change? Why? --> ## Type of Change - [ ] Bug fix - [ ] New feature - [ ] Breaking change - [ ] Documentation update ## Testing <!-- How did you test these changes? --> ## Checklist - [ ] Code follows style guidelines - [ ] Self-review completed - [ ] Tests added/updated
When to use: Standardize PR descriptions across your team. GitHub auto-loads this template when someone opens a new PR.
Step 42 | Set Up CODEOWNERS for Auto-Reviewers
File: .github/CODEOWNERS
Example content:# Root files * @userRizwan # Documentation /docs @userRizwan @docs-team # Source code /src @dev-team
When to use: Automatically request reviews from specific people/teams when files they own are modified. Place in .github/ or root directory.
Step 43 | Enable GitHub Actions (CI/CD)
File: .github/workflows/ci.yml
Example (Node.js test workflow):name: CI Tests on: [push, pull_request] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Setup Node.js uses: actions/setup-node@v4 with: { node-version: '20' } - run: npm ci - run: npm test
When to use: Automatically run tests, linting, or deployments on every push or PR. No server setup required—GitHub hosts the runners.
Step 44 | Trigger Actions Manually (Workflow Dispatch)
Add to workflow YAML:on: workflow_dispatch: # Enables manual trigger push: branches: [main]
When to use: Run a workflow on-demand (e.g., deploy to staging) via GitHub UI: Actions tab → Select workflow → “Run workflow” button.
Step 45 | Use GitHub Secrets for Sensitive Data
UI Path: Repo → Settings → Secrets and variables → Actions → New repository secret
Command in workflow:- name: Deploy run: ./deploy.sh env: API_KEY: ${{ secrets.MY_API_KEY }}
When to use: Store API keys, passwords, or tokens securely. Never hardcode secrets in your repo—GitHub encrypts and injects them at runtime.
Step 46 | Publish a Website with GitHub Pages
UI Path: Repo → Settings → Pages → Build and deployment
Options:
Source: Deploy from a branch
Branch: main + /root or /docs
Or use GitHub Actions for custom builds (Jekyll, Hugo, Next.js)
When to use: Host static websites, documentation, or project portfolios for free with automatic HTTPS.
Step 47 | Create GitHub Releases with Assets
UI Path: Repo → Releases → Draft a new release
Steps:
Tag version: v1.0.0 (or create new tag)
Title: Version 1.0.0 - Stable Release
Description: Use auto-generated changelog or write manually
Attach binaries: .exe, .zip, .dmg, etc.
✅ Check “Set as latest release”
When to use: Distribute compiled software, installers, or versioned downloads to users.
Step 48 | Use GitHub Issues Templates
File: .github/ISSUE_TEMPLATE/bug-report.md
Example:--- name: Bug Report about: Create a report to help us improve title: '[BUG] ' labels: bug --- ### Describe the bug <!-- Clear description of the issue --> ### Steps to Reproduce 1. Go to '...' 2. Click on '...' 3. See error ### Expected behavior <!-- What should have happened? --> ### Environment - OS: [e.g. Windows 11] - Browser: [e.g. Chrome 120]
When to use: Guide users to submit high-quality bug reports or feature requests, reducing back-and-forth clarification.
Step 49 | Link Issues to Pull Requests
In PR description or commit message:Fixes #123 Closes #456 Resolves userRizwan/other-repo#789
When to use: Automatically close linked issues when the PR merges. Keeps your project board clean and traceable.
Step 50 | Use GitHub Projects for Task Management
UI Path: Repo → Projects → New project (or organization-level)
Features:
Kanban boards (To Do / In Progress / Done)
Auto-link issues/PRs to cards
Custom fields (priority, effort, assignee)
Roadmap view for timelines
When to use: Plan sprints, track bugs, manage features—without leaving GitHub. Integrates natively with Issues and PRs.
🔐 SECURITY & BEST PRACTICES (Non-Negotiable)
Step 51 | Enable Branch Protection Rules
UI Path: Repo → Settings → Branches → Add rule
Recommended settings for main:
✅ Require a pull request before merging
✅ Require approvals (1-2 minimum)
✅ Require status checks to pass (CI tests)
✅ Require conversation resolution before merging
✅ Include administrators (no bypassing)
✅ Restrict who can push (optional)
When to use: Prevent accidental or unauthorized changes to critical branches. Essential for team projects.
Step 52 | Scan for Secrets Before Pushing
Tool: git-secrets or GitHub’s built-in secret scanning
Install git-secrets:brew install git-secrets # macOS git secrets --install git secrets --register-aws # Add AWS patterns
When to use: Catch API keys, passwords, or tokens BEFORE they reach GitHub. Prevention > damage control.
Step 53 | Use Dependabot for Automated Security Updates
UI Path: Repo → Settings → Code security and analysis → Dependabot alerts → Enable
Config file: .github/dependabot.yml
Example:version: 2 updates: - package-ecosystem: "npm" directory: "/" schedule: { interval: "weekly" } - package-ecosystem: "github-actions" directory: "/" schedule: { interval: "monthly" }
When to use: Automatically create PRs to update vulnerable dependencies. Keeps your project secure with minimal effort.
Step 54 | Sign Commits with GPG (Verify Authenticity)
Generate GPG key:gpg --full-generate-key # Follow prompts gpg --list-secret-keys --keyid-format=long
Add to Git:git config --global user.signingkey YOUR_KEY_ID git config --global commit.gpgsign true
Add public key to GitHub: Settings → SSH and GPG keys → New GPG key
When to use: Prove that commits truly came from you. GitHub shows “Verified” badge on signed commits.
Step 55 | Review Audit Log for Account Activity
UI Path: GitHub.com → Settings → Account security → Audit log
When to use: Monitor logins, repo changes, permission updates. Critical for detecting unauthorized access or insider threats.
🛠️ TROUBLESHOOTING COMMON ISSUES
Issue: “fatal: remote origin already exists”
Solution:git remote set-url origin https://github.com/username/new-repo.git
When to use: You changed the GitHub repo URL but Git still points to the old one.
Issue: “error: failed to push some refs” after force update
Solution:git pull --rebase origin main # Resolve conflicts if any, then: git push
When to use: Someone else pushed to the same branch. Rebase your work on top of theirs instead of forcing.
Issue: Accidentally committed a large file or secret
Solution (if NOT pushed):git reset --soft HEAD~1 # Remove the file, then recommit
Solution (if ALREADY pushed):# 1. Remove file from history (use BFG or filter-branch) # 2. Force push (ONLY if you're the sole collaborator): git push --force-with-lease # 3. Rotate any exposed secrets immediately!
⚠️ Warning: Force-pushing rewrites history. Coordinate with teammates first.
Issue: “Your branch is ahead/behind” confusion
Solution:# See exact difference: git log --oneline --left-right --cherry-pick main...origin/main # Sync safely: git fetch origin git merge origin/main # or git rebase origin/main
When to use: Understand exactly what commits differ between local and remote before pushing.
Issue: Merge conflict in binary file (e.g., .psd, .docx)
Solution:# Choose one version entirely: git checkout --ours filename.psd # Keep your version # OR git checkout --theirs filename.psd # Keep incoming version git add filename.psd git commit -m "Resolve binary conflict"
When to use: Git can’t merge binary files automatically. Pick one version and document the decision.
🚀 PRO TIPS: WORK SMARTER, NOT HARDER
✅ Use Git Aliases (Save keystrokes):
Add to ~/.gitconfig:[alias] co = checkout br = branch ci = commit st = status lg = log --graph --oneline --all unstage = reset HEAD -- last = log -1 HEAD
Usage: git co main instead of git checkout main
✅ Pre-commit Hooks for Quality Control:
File: .git/hooks/pre-commit (make executable)
Example (lint JS before commit):#!/bin/sh npm run lint if [ $? -ne 0 ]; then echo "Lint failed. Commit aborted." exit 1 fi
When to use: Enforce coding standards, run tests, or block commits with secrets—automatically.
✅ Use git worktree for Parallel Tasks:git worktree add ../hotfix-branch main # Work in ../hotfix-branch while keeping main branch open elsewhere git worktree remove ../hotfix-branch # When done
When to use: Fix a critical bug in main while mid-feature on another branch—without stashing or switching.
✅ Leverage GitHub CLI (gh) for Speed:
Install: brew install gh (macOS) or winget install GitHub.cli (Windows)
Useful commands:gh repo create my-new-project --public --clone gh pr create --title "Fix login bug" --body "Resolves #123" gh issue list --state open --label bug gh actions run watch # Monitor CI in terminal
When to use: Perform GitHub actions without leaving your terminal. Faster than UI for repetitive tasks.
✅ Document Your Workflow in CONTRIBUTING.md:
File: CONTRIBUTING.md at repo root
Include:
How to set up the project locally
Branch naming conventions (feature/, fix/, docs/)
Commit message format (Conventional Commits)
PR checklist and review process
When to use: Onboard new contributors faster and reduce repetitive questions.
📚 FINAL CHECKLIST: BEFORE YOU PUSH TO PRODUCTION
[ ] All tests pass locally (npm test, pytest, etc.)
[ ] Code is linted and formatted (eslint --fix, prettier --write)
[ ] No secrets or sensitive data in commits (use git-secrets)
[ ] Commit messages are clear and follow team convention
[ ] Branch is rebased/merged with latest main
[ ] Pull Request has description, screenshots (if UI), and linked issues
[ ] Required reviewers have approved (if branch protection enabled)
[ ] CI/CD checks pass on GitHub Actions
[ ] You’ve tested the change in a staging environment (if applicable)
🎯 BONUS: 30-Second Git Command Cheat Sheet# Start git init # New repo git clone <url> # Download repo # Daily Loop git status # What changed? git add . # Stage all git commit -m "msg" # Save snapshot git push # Upload to GitHub # Branching git branch -a # List all branches git switch -c feature/new # Create + switch git merge feature/new # Merge into current # Sync git fetch # Download updates git pull # Fetch + merge git push -u origin branch # First push with tracking # Undo git restore file.txt # Discard local edits git reset --soft HEAD~1 # Undo commit, keep changes git revert <hash> # Undo public commit safely # Inspect git log --oneline --graph # Visual history git diff # See unstaged changes git show <hash> # View commit details # Advanced git rebase main # Clean up branch history git cherry-pick <hash> # Copy one commit git stash # Temporarily save work
🎉 Congratulations! You now have a complete, production-ready GitHub toolkit—from “Hello World” to enterprise workflows.
Next Steps for Mastery:
Practice daily: Use Git for every project, even small ones.
Contribute to open source: Start with “good first issue” labels on GitHub.
Teach someone: Explaining git rebase to a friend cements your understanding.
Explore GitHub Marketplace: Add bots for auto-labeling, PR size limits, or welcome messages.
“The best time to start using Git was yesterday. The second best time is right now.” — Neil Patel
