C
Collaboration & Git/Git Basics/Lesson 02

Git Essentials — Commands, .gitignore, and GitHub All in One

30 min·theory

Git Essentials — Commands, .gitignore, and GitHub All in One

🎯 By the End of This Lesson

After finishing this lesson, you will be able to confidently do the following three things.

  • ✅ Git's three areas: working directory / staging area / repository
  • ✅ Basic commands: commit · branch · merge
  • ✅ Writing Conventional Commits messages

Keep the learning objectives as a checklist, and close the lesson once you can answer all of them.

The 6-Step Daily Git Workflow

1. Edit — Modify code in the Working Directory
2. git add — Move changed files → Staging Area
3. git commit -m — Move from Staging → Local Repo. Summarize changes with a message
4. git push — Local → Remote (GitHub). Share with your team
5. git pull — Remote changes → Local. Sync teammates' work
6. branch / merge — Branch by feature, merge into main when done

> 💡 Key concept: Edit (Working) → Stage (Staging) → Save (Repo) → Share (Remote) — a 4-step model.

💻 📌 Essential Git Commands
# ============================================
# What this command does: Full flow of basic Git workflow
# Real-life analogy: Document work → review → save → share process
# ============================================

# === Basic Workflow ===
# Check current working directory status (which files have changed)
git status                    # Check current status
# Stage only specific files (add to review area before commit)
git add file.txt              # Stage specific file
# Stage all changed files at once
git add .                     # Stage all changed files
# -m flag = write commit message inline (otherwise vim editor opens)
git commit -m "Message"        # Create commit
# Result: [main abc1234] Message / 1 file changed, 1 insertion(+)

# === Check History ===
# Check full commit history (including author, date, message)
git log                       # View commit history
# --oneline = summarize commit ID + message in one line
git log --oneline             # View in one line
# --graph = visualize branch branching/merging with ASCII art
git log --graph               # View as graph
# Detailed check of changes (diff) and metadata for a specific commit ID
git show abc123               # View specific commit details

# === Remote Repository ===
# List of connected remote repository URLs (output fetch/push URLs separately)
git remote -v                 # List remote repositories
# Upload local commits to the main branch of origin (remote)
git push origin main          # Push to remote
# Fetch remote changes and automatically merge into current branch
git pull origin main          # Pull from remote
# Only fetch remote info, do not auto-merge (can merge after safe check)
git fetch origin              # Only fetch remote info

# === Undo Changes ===
# Discard Working Directory changes (restore to pre-staging state)
git checkout -- file.txt      # Undo file changes
# Remove from Staging Area and revert to Working Directory
git reset HEAD file.txt       # Unstage
# Rewrite the last commit message (safe only if commit not pushed)
git commit --amend            # Amend last commit

.gitignore — Things You Must Never Push

1. New project — Copy and paste a template from github.com/github/gitignore (Node, Python, Java, etc.)
2. Pattern syntax*.log (extension) / node_modules/ (folder) / !important.log (exception)
3. Verify — Check with git status. If files that should be ignored appear as untracked, they are missing from .gitignore
4. Already-committed files — Adding to .gitignore won't stop tracking. Use git rm --cached <file> to untrack
5. Global .gitignore~/.gitignore_global (shared across all projects, e.g. .DS_Store)
6. CI scanning — Scan for secret files with GitHub Actions using truffleHog or git-secrets

> ⚠️ Common mistake: missing .env, .key, .pem, .aws/credentials → secrets exposed. Once pushed, they remain in git history permanently.

6 Core GitHub Features

1. Repository — Project storage. public/private. README · LICENSE · .gitignore · .github/. fork · star · watch
2. Issues — Bugs, feature requests, discussions. label · milestone · assignee. Auto-linked to PRs (Closes #123)
3. Pull Request — Request to merge changes from a fork or branch into the original. Code review · CI · merge after approval
4. Actions (CI/CD).github/workflows/*.yml — auto build, test, deploy on push or PR. Free for public repos
5. Codespaces — VS Code + container inside the browser. No local setup required. Instant PR review and contribution
6. Copilot — AI pair programmer. Code autocomplete · PR summary · issue answers

> 🔗 GitHub founders: Tom Preston-Werner, Chris Wanstrath, PJ Hyett, Scott Chacon (2008) → acquired by Microsoft in 2018 → 100M+ developers in 2025.

git reset · revert · cherry-pick · stash — The *Four Undo Commands*

git reset — Time Travel to the Past

bash
git reset --soft  HEAD~1     # Undo commit only, keep stage·work
git reset --mixed HEAD~1     # Undo commit·stage, keep work (default)
git reset --hard  HEAD~1     # Delete all — *Dangerous*

Comparing the 3 Options

OptionHEADIndex (Staged)Working Dir
--softmovedkeptkept
--mixed (default)movedresetkept
--hardmovedresetreset

The most common scenarios:

bash
# I only want to rewrite the last commit message
git reset --soft HEAD~1
# Same changes are staged → git commit again

# Undo the last commit entirely and keep only the changes
git reset HEAD~1     # --mixed default
# Working copy remains, stage cleared → work again

# I really want to delete everything (the ultimate CTRL+Z)
git reset --hard origin/main
# *Only when remote is a safe starting point*

⚠️ Danger of reset --hard

  • Uncommitted changes are lost permanently
  • Resetting an already-pushed commit — conflicts with others + requires force push + breaks history

Never reset on shared branches. Local only.

git revert — Safe Undo for Public Branches

bash
git revert <commit-hash>

Adds a new "reverting commit". History is preserved; only the change is undone.

code
# before revert:  A → B → C
# revert C:       A → B → C → C'  (opposite change of C)

The standard approach when undoing a bad commit on the main branch. Works cleanly with other people's git pull.

reset vs revert in One Line

  • resetRewrites history. Local only.
  • revertAdds a new reverting commit. Safe anywhere.

git cherry-pick — Pick a Specific Commit

bash
# Only commit abc1234 from feature branch to main
git checkout main
git cherry-pick abc1234

Commonly used to backport a hotfix to a stable branch, or to merge only part of a large PR first.

bash
# Multiple
git cherry-pick abc1234..def5678        # Range
git cherry-pick abc1234 def5678 ghi9012  # List

git stash — Temporary Save

Scenario: You're mid-work and suddenly need to switch branches.

bash
git stash             # Temporarily save changes
git checkout other
# ... other work ...
git checkout original
git stash pop          # Restore

The standard way to move cleanly without committing.

bash
git stash list             # List saved stashes
git stash apply stash@{2}  # Apply specific stash (pop applies+deletes)
git stash drop stash@{0}   # Delete specific stash
git stash branch tmp       # Split stash into a new branch

.gitignore Practical Patterns

code
# Dependencies
node_modules/
.venv/
__pycache__/
*.pyc

# Build results
dist/
build/
.next/
target/

# Environment variables·secrets
.env
.env.local
.env.*.local
*.pem
*.key

# IDE
.vscode/
.idea/
*.swp
.DS_Store

# Logs
*.log
logs/

# Cache
.cache/
.parcel-cache/

Write this immediately when starting a project. Use https://gitignore.io to auto-generate by tech stack.

Commit Messages — bad/good

code
❌ "Fixed"
✅ fix(auth): handle null user in login flow

❌ "Added feature"
✅ feat(payment): add Stripe webhook handler

❌ "Bug"
✅ fix(api): correct 500 error when user_id is missing

❌ "Refactoring"
✅ refactor(db): extract user query into repository

Conventional Commits standard:

code
<type>(<scope>): <description>

types: feat, fix, docs, style, refactor, test, chore, perf

50 characters for the first line, wrap body at 72 characters. Use the imperative present tense in English.

🤖 Try Asking AI

  • "What git command cancels the last commit but keeps the changes in the staging area?"
  • "Write a Conventional Commits message for these changes."
  • "Review whether this .gitignore is sufficient for a Node.js + Python + Java environment."
Git Essentials — Commands, .gitignore, and GitHub All in One - Collaboration & Git