Git Basics

Git tracks changes to your files so you can save versions, experiment without fear, and collaborate with others.

First-Time Setup

Tell Git who you are (do this once):

git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"

Creating a Repository

A "repository" (repo) is a folder that Git is watching.

mkdir my-project
cd my-project
git init                    # Turn this folder into a Git repo

The Basic Workflow

Git has three areas: - Working directory — your actual files - Staging area — files you've marked to save - Repository — the saved history

Working → git add → Staging → git commit → Repository

Step 1: Check status

git status                  # See what's changed

Step 2: Stage files

git add filename.py         # Stage one file
git add .                   # Stage all changed files

Step 3: Commit (save)

git commit -m "Add login feature"

Step 4: View history

git log                     # Full history
git log --oneline           # One line per commit

Undoing Changes

git checkout -- file.py     # Discard changes to file.py (before staging)
git reset HEAD file.py      # Unstage a file (keep changes)
git reset --hard            # Discard ALL uncommitted changes ⚠️

Working with Remote Repositories (GitHub)

Clone an existing project

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

Push your code to GitHub

# Create a repo on GitHub first, then:
git remote add origin https://github.com/username/repo.git
git branch -M main
git push -u origin main

Pull changes from GitHub

git pull                    # Get latest changes

Branches

Branches let you work on features independently.

git branch                          # List branches
git branch feature-login            # Create a new branch
git checkout feature-login          # Switch to that branch
git checkout -b feature-login       # Create AND switch (shortcut)

# Merge a branch back to main
git checkout main
git merge feature-login

# Delete a branch
git branch -d feature-login

Common Patterns

# Save all changes with one command
git add -A && git commit -m "Describe your changes"

# See what changed in a file
git diff filename.py                # Unstaged changes
git diff --staged filename.py       # Staged changes

# See what changed in the last commit
git show

# Ignore files (create .gitignore)
echo "venv/" > .gitignore
echo ".env" >> .gitignore
echo "__pycache__/" >> .gitignore

Best Practices

  1. Commit often — small, focused commits (not "fixed stuff")
  2. Write good messages — "Add password validation" not "Update file"
  3. One branch per feature — keep main clean
  4. Never commit secrets — API keys, passwords, .env files go in .gitignore

Your Turn — Mini Exercise

mkdir -p /tmp/git-practice && cd /tmp/git-practice
git init
echo "# My Project" > README.md
git add README.md
git commit -m "Initial commit"
echo "print('hello')" > app.py
git add app.py
git commit -m "Add hello script"
git log --oneline